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
  • 58,414
  • 16
  • 114
  • 157
Aleksei Chepovoi
  • 3,915
  • 8
  • 39
  • 77

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
  • 362,217
  • 114
  • 495
  • 492