Run once when loading AngularJS controller

I have something that needs to be done only once when the controller is loaded. What is the best way to do this? I read something about the “launch block”, but I really don’t understand how it works.

Some pseudo codes:

when /app
resolove some stuff
load a view
controllerA

ControllerA:

Some-magic-piece-of-code-only-run-once{
 }

Can someone point me in the right direction?

+4
source share
2 answers

Just do it fine, controllers are just functions that are introduced using $ scope, services. When the controller is loaded, this function is called only once . You can do anything in it.

app.controller("yourController",function($scope, myService){
   //Write your logic here.


   //Initialize your scope as normal
});
+1
source

I always use ngInit .

HTML:

<div ng-controller="AppController" ng-init="init()"/>

JS:

$scope.init = function () {
  // do something
};

, , :

var AppController = function($scope) {
  // do something very early

  $scope.init = function () {
    // do something on loaded
  };

};
+12

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


All Articles