Run code on angular application startup

Is there a way that I can execute some JavaScript code when running my AngularJS application? I have a generic code that I need to make sure that it runs before any application directives / controllers. I don’t want to be attached to routes and ng-view , I need this to be a general solution for any ng-app .

I thought I could use Module Config, and I really tried this, but I'm trying to call a service that seems impossible to access module loading.

+49
angularjs
Oct 09 '13 at 15:20
source share
4 answers

You can do it,

 var app = angular.module('myApp',[]); app.run(function($rootScope) { //..... }); 
+73
Oct 09 '13 at 15:46
source share

Short version

You need to use the module.run(initializationFn) function, where the actual method may depend on the services. You can enter dependencies as usual:

 var app = angular .module('demoApp', []) .run(['$rootScope', function($rootScope) { $rootScope.bodyClass = 'loading'; // Etc. Initialize here. }]); 

The example has initialization depending on $rootScope , but you can also enter services, etc.

Longer version

The relevant module.run documentation is quite complicated, as are the other (excellent) answers. Let me combine it into a more detailed example, which also shows how to enter the factory created service in initializationFn :

 var app = angular.module('demoApp', []); // Service that we'll also use in the .run method app.factory('myService', [function() { var service = { currentItem: { started: new Date() } }; service.restart = function() { service.currentItem.started = new Date(); }; return service; }]); // For demo purposes app.controller('demoCtrl', ['$scope', 'myService', function($scope, myService) { $scope.header = 'Demo!'; $scope.item = myService.currentItem; $scope.restart = myService.restart; }]); // This is where your initialization code goes, which // may depend on services declared on the module. app.run(['$window', 'myService', function($window, myService) { myService.restart(); $window.alert('Started!'); }]); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="demoApp" ng-controller='demoCtrl' ng-cloak> <h1>{{ header }}</h1> <p>Current item started: {{ item.started }}</p> <p><button ng-click="restart()">Restart</button></p> </div> 
+22
Jul 19 '15 at 9:58
source share

You can use the run function from the module API: http://docs.angularjs.org/api/angular.Module

This code will be executed after the injector is created so that you can access the service you want to use.

+3
09 Oct '13 at 15:43
source share

The Yor controller looks like a function, adds a function call at the bottom of the controller, and you have a start function!

0
Jun 28 '17 at 20:24
source share



All Articles