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?
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
};
};
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With