5

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?

1
  • 1
    The code you put in the controller is run only once when the controller is loaded. What exactly do you mean? What have you tried? Post some code. Commented Jan 28, 2014 at 9:44

3 Answers 3

14

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
  };

};
Sign up to request clarification or add additional context in comments.

1 Comment

This should be the correct answer. ng-init is called once no matter how many times the directive gets re-rendered
1

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
});

11 Comments

Ah. That was easy. Sometimes you make things more complicated then they are. Thx!
As @meilke suggested ng-init is best practice.
@Satyajitsinh Raijada: I don't think so, so does angular official page: The only appropriate use of ngInit is for aliasing special properties of ngRepeat: docs.angularjs.org/api/ng/directive/ngInit
Controllers can actually be executed multiple times. For example always when ui-router state changes.
@Petr Peller: Can you tell me what is your case? It looks to me there is something wrong in the application design. If your code is to initialize the controller, it should be rerun whenever the controller is reinitialized, otherwise, the first instance behaves differently than the second instance. If your controller initialization code modifies some global state, you should be consider whether it's the right place to implement your code.
|
0

Sorry for late response. If you want some functionality to run only once (on application load time) and it depends on some functionality in controller then you'll need to put that functionality in a service/factory and you'll inject that service in the run block (associated to that service) which will be executed just after the service is loaded. If you won't inject service in run block then run block will be executed first independent of your service. So this is what will serve your purpose:

angular.module('myangularapp')
.factory('myLogger', ['$http', 'apiUrl',
function ($http, apiUrl) {
    'use strict';
    function PostService() {
        $http({
            url: apiUrl + 'TestEndPoint',
            dataType: 'json',
            method: 'post',
            data: //some object
        }).then(function success(response) {
        }, function errorCallback(errorThrown) {
        });
    }

    return {
        PostService: PostService
    }
}])
.run(function (myLogger, $rootScope) {
myLogger.PostService();
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.