在角度应用启动时执行代码

Mic*_*bib 53 angularjs

有没有办法在我的AngularJS应用程序启动时执行一些JavaScript代码?我有一些常见的代码,我需要确保在任何app指令/控制器之前运行.我不想被束缚到路线上ng-view,我需要这个是任何通用解决方案ng-app.

我以为我可以使用Module Config,我实际上尝试过,但我试图调用一个服务,这似乎无法在Module Load上访问.

dev*_*evo 80

你可以这样做,

var app = angular.module('myApp',[]);

app.run(function($rootScope) {
    //.....
});
Run Code Online (Sandbox Code Playgroud)

  • 这给了我调用控制器的竞争条件.当函数执行时,似乎并非所有控制器都准备就绪. (5认同)

Jer*_*oen 25

精简版

您需要使用该module.run(initializationFn)函数,其中实际方法可以依赖于服务.您可以按常规注入依赖项:

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

该示例依赖于初始化$rootScope,但您也可以注入服务等.

更长的版本

相关module.run文档相当简洁,其他(优秀)答案也是如此.让我把它组合成一个更详细的例子,它还展示了如何factory在你的注入中创建一个已创建的服务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!');
}]);
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)