Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run once when AngularJS controller loads

Tags:

angularjs

I have some stuff that needs to be done only once when the controller is loaded. What's the best way to this? I've read some about the "run block" but I don't really understand how it works.

Some pseudo code:

when /app
resolove some stuff
load a view
controllerA

ControllerA:

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

Can anyone point me in the right direction?

like image 887
Joe Avatar asked Jan 28 '14 09:01

Joe


2 Answers

I always use ngInit for this.

HTML:

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

JS:

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

The code specified in your controller function is run only once, too:

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

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

};
like image 134
meilke Avatar answered Oct 26 '22 03:10

meilke


Just do it normally, controllers are just functions injected with $scope, services. When the controller is loaded, this function is called only once. You can do anything inside it.

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


   //Initialize your scope as normal
});
like image 33
Khanh TO Avatar answered Oct 26 '22 02:10

Khanh TO