How to make a controller function execute only once in AngularJS?

I have a controller referenced by some html. And html changes to some event, so the controller function code is executed several times.
The problem is that I have a world 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 is executed every time the html changes.
Here's how the controller is inserted:

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

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

+4
source share
1 answer

Put your "run once" code in service and return the promise.

Enter this service in the controller.

An example of creating a service and then returning a promise, and then a controller using this promise, see If services display their asynchrony?

+3
source

Source: https://habr.com/ru/post/1493015/


All Articles