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?
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?
- 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 – Abhishek Nandi 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) – Aleksei Chepovoi 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 – Abhishek Nandi Commented Jul 23, 2013 at 17:34
1 Answer
Reset to default 3Put 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?