d4rty d4rty - 1 year ago 113
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

I have an
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
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) {
.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 Source

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() {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download