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

數組中字符串的順序需要與函數中參數的順序相匹配。 –

相關問題