0

我正在构建一个非常简单的应用程序,其中我有一个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()); 

}]); 

回答

1

在你最后的代码块,你需要注入$范围以及。你可以注入任意数量的,你需要的服务:

globalModule.controller('GlobalController', ['squareMgr', '$scope', 
    function($squareMgr, scope){ 

    // but then how do I get $scope in there? 

    log('GlobalController loaded'); 
    // log($squareMgr.getSquaresEarned()); 

}]); 

而一个小点,我不会把一个$在squareMgr的面前,$意味着它是一个内置的角度服务。

+0

由于区分,但是,我应该使用$范围在控制器? – Scott

+0

当然,您几乎总是会在控制器内使用$ scope。这是Angular的核心部分。 –

0

尝试

globalModule.controller('GlobalController', ['squareMgr', '$scope', function($scope, squareMgr){ ..... 

$符号用于角服务和自己的

+1

数组中字符串的顺序需要与函数中参数的顺序相匹配。 –

相关问题