ショートバージョンが
あなたは、実際の方法は、サービスに依存することができmodule.run(initializationFn)
機能を使用する必要があります。あなたは通常通りの依存関係を注入することができます
var app = angular
.module('demoApp', [])
.run(['$rootScope', function($rootScope) {
$rootScope.bodyClass = 'loading';
// Etc. Initialize here.
}]);
例は$rootScope
に初期化依存持っていますが、あなたはまた、サービスを注入することができるなど
長いバージョン
The relevant module.run
documentationは、かなり簡潔であるとして他の(優秀な)回答。私は、より詳細な例にそれを組み合わせてみましょう、それはまたあなたのinitializationFn
でfactory
作成されたサービスを注入する方法を示しています。
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>
これは私のコントローラへの呼び出しのための競合状態を示します。関数が実行されたときに、すべてのコントローラが準備完了状態にあるとは限りません。 – Dan
@ダン、コントローラで解決を使用していますか? – lyyons
@lyyonsこれはルートでしか機能しませんか? – Dan