4

I have a controller that is referenced in some html. And the html changes on some event so the controller function code executes multiple times.
The problem is that I have a peace of code that needs to be executed only once.
Here is the controller:

angular.module("someModule", [dependencies])
.controller("leftBoardController", function ($scope, someService) {
   (function createFilter(dataService) {
    // here I'm loading all the data on which I want to operate after
            // this code should execute only once
    })(TempEmployeeService);
}

But it executes each time the html changes.
This is how the controller is inserted:

<section ng-controller="TreeMapController"
                 ng-class="{ 'main-container-single': zoomed }"
                 class="minContainer main-container">

Questions:
1) How to make the controller function execute only once?
2) Or is there a way I can write this peace of code that will execute only once?

isherwood
  • 52,576
  • 15
  • 105
  • 143
Aleksei Chepovoi
  • 3,835
  • 8
  • 36
  • 76

1 Answers1

3

Put your "run once" code into a service, and return a promise.

Inject that service into your controller.

For an example of a service creating and then returning a promise, and the controller then using that promise, see Should services expose their asynchronicity?

Community
  • 1
  • 1
Mark Rajcok
  • 356,856
  • 113
  • 487
  • 490