Execute code at startup of angular application

前端 未结 3 852
孤独总比滥情好
孤独总比滥情好 2021-01-31 13:44

Is there a way I can execute some JavaScript code at start-up of my AngularJS application? I have some common code that I need to make sure runs before any of the app directives

相关标签:
3条回答
  • 2021-01-31 14:27

    You can do like this,

    var app = angular.module('myApp',[]);
    
    app.run(function($rootScope) {
        //.....
    });
    
    0 讨论(0)
  • 2021-01-31 14:29

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

    This code will be executed after injector creation so you should be able to get at the service you are looking to use.

    0 讨论(0)
  • 2021-01-31 14:49

    Short version

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

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

    The example has initialization dependent on $rootScope, but you can also inject services, etc.

    Longer version

    The relevant module.run documentation is rather terse, as are the other (excellent) answers. Let me combine it into a more verbose example, that also shows how to inject a factory created service in your 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>

    0 讨论(0)
提交回复
热议问题