我正在构建一个非常简单的应用程序,其中我有一个GlobalController(在body元素上),并且下面还有另一个子控制器。这是一个带有多个物理页面的模板化网站,这样子控制器将有所不同,但最多只有一个顶级全局和一个子控制器。AngularJS服务 - 在控制器中使用
我想使全局函数的任何子控制器可以用来运行代码,每个需要运行,而不必在每个子控制器中复制功能。
我可以做到这一点的一种方法是包含$ rootScope,然后将消息发送给使用$ on()监听它们的GlobalController。
我收集这不是一个“好”的方式来做到这一点。相反,我已经了解到为此使用服务会更好。我现在被困在如何实现这项服务。
我现在有一个全局控制器,像这样:
var globalModule = angular.module('DoSquareStuff', ["ngRoute","list", "savings-video"]);
// there will be a long list of modules that will be added after "savings-video"
globalModule.factory('squareMgr', function() {
var squares = SUYS.squares; // global obj with earned[] and placed[]
return {
getSquaresEarned: function() {
return squares.earned;
},
getSquaresPlaced: function() {
return squares.placed;
},
setThisSquareEarned: function(value) {
squares.earned.push(value);
},
setThisSquarePlaced: function(value) {
squares.placed.push(value);
},
earnedThisSquare: function(squareNum) {
return ~squares.earned.indexOf(squareNum);
},
placedThisSquare: function(squareNum) {
return ~squares.placed.indexOf(squareNum);
}
}
});
globalModule.controller('GlobalController', function($scope, $squareMgr){
// this would be easy... but it doesn't work
// $rootScope.$on('signal.missionComplete', function (event, missionId) {
// console.log("parentScope receive notice that mission " + missionId + " is complete.");
// });
log('GlobalController loaded');
// log($squareMgr.getSquaresEarned()); //broken
});
然后,阅读文档,我想:
globalModule.controller('GlobalController', ['squareMgr', function($squareMgr){
// but then how do I get $scope in there?
log('GlobalController loaded');
// log($squareMgr.getSquaresEarned());
}]);
由于区分,但是,我应该使用$范围在控制器? – Scott
当然,您几乎总是会在控制器内使用$ scope。这是Angular的核心部分。 –