Versione corta
è necessario utilizzare la funzione module.run(initializationFn)
, dove il metodo effettivo può dipendere da servizi. È possibile iniettare le dipendenze come al solito:
var app = angular
.module('demoApp', [])
.run(['$rootScope', function($rootScope) {
$rootScope.bodyClass = 'loading';
// Etc. Initialize here.
}]);
L'esempio dispone di inizializzazione dipende $rootScope
, ma è anche possibile iniettare servizi, ecc
Longer versione
The relevant module.run
documentation è piuttosto laconico, come lo sono i altre (eccellenti) risposte. Mi permetta di combinare in un esempio più dettagliato, che dimostra anche come iniettare un servizio creato factory
nel 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>
Questo mi dà condizioni di gara per le chiamate verso i controllori. Sembra che non tutti i controller siano pronti quando la funzione viene eseguita. – Dan
@Dan, stai usando le risoluzioni sui tuoi controller? – lyyons
@lyyons Non funziona solo per le rotte? – Dan