d4rty d4rty - 3 months ago 15
AngularJS Question

AngularJS execute function in controller only once in the context of Routing

I'm using the routing feature of AngularJS. Furthermore I want only on controller for all templates.

In my controller

angularJsController
I have an
init
function, which should only be executed at the first time the controller gets executed and when I explicitly call the function. But I don't wan't that the
init
function will be executed each time the routing loads another template.

How can I achieve the desired behaviour?

var app = angular.module("angularJsApplication", ["ngRoute"]);

app.config(function($routeProvider) {
$routeProvider
.when("/overview", {
templateUrl : "overview.html",
controller : "angularJsController"
.when("/settings", {
templateUrl : "settings.html",
controller : "angularJsController"
...
});

app.controller("angularJsController", function ($scope, $location, $http) {
$scope.init = function() {
//do stuff
};
}

Answer

Create a service to do the things that should only be executed once. Services are stored as singletons, but you can provide one or more ways to re-execute code.

app.factory("initService", [function() {
    var returnObject = {}
    // set properties of returnObject
    // do something like this if you need "explicitly call the function"
    returnObject.recaculate = function() {
        // perform recaculations
    } 
    return returnObject;
}]);

Don't forget to inject the service into your controller(s):

app.controller("angularJsController", ["$scope", "$location", "$http", "initService", function ($scope, $location, $http, initService) {
    // controller contents
    $scope.reInit = function() {
       initService.recaculate();
    }
}]);