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?

3
  • what do you mean by html changes ?? do you mean part of you page as in a section mentioned above changes or the whole page changes Commented Jul 23, 2013 at 17:14
  • 1
    I think the whole page. I change the url in my code and the html changes (the page is not reloaded) Commented Jul 23, 2013 at 17:20
  • if the page is refreshed/loaded/loaded the controller will be called again- that is what is expected Commented Jul 23, 2013 at 17:34

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

1 Comment

I did it with an array variable, it is more understandable for me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.