我想將包含在工廠中的函數庫包含到控制器中。 到這樣的問題類似: Creating common controller functions
我主控制器看起來是這樣的:
recipeApp.controller('recipeController', function ($scope, groceryInterface, ...){
$scope.groceryList = [];
// ...etc...
/* trying to retrieve the functions here */
$scope.groceryFunc = groceryInterface; // would call ng-click="groceryFunc.addToList()" in main view
/* Also tried this:
$scope.addToList = groceryInterface.addToList();
$scope.clearList = groceryInterface.clearList();
$scope.add = groceryInterface.add();
$scope.addUp = groceryInterface.addUp(); */
}
然後,在另一個.js文件中,我創建了工廠groceryInterface。我已經將這個工廠注入到上面的控制器中。
廠
recipeApp.factory('groceryInterface', function(){
var factory = {};
factory.addToList = function(recipe){
$scope.groceryList.push(recipe);
... etc....
}
factory.clearList = function() {
var last = $scope.prevIngredients.pop();
.... etc...
}
factory.add = function() {
$scope.ingredientsList[0].amount = $scope.ingredientsList[0].amount + 5;
}
factory.addUp = function(){
etc...
}
return factory;
});
但在我的控制檯我不斷收到ReferenceError: $scope is not defined at Object.factory.addToList
等很顯然,我猜測這與事實,我用我的功能$scope
內做廠。我該如何解決這個問題?我注意到,在我看過的許多其他例子中,沒有人在其外部工廠功能中使用$scope
。我已經嘗試在我的工廠注入$scope
作爲參數,但是這顯然不起作用。 (例如recipeApp.factory('groceryInterface', function(){
)
任何幫助真正感激!
甜,謝謝。我會試試這個! – LazerSharks
@Gnuey - 請注意,'bind'在舊版本的IE中不可用。如果您必須支持這些方法並希望使用第一種方法,請使用[此MDN填充](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#兼容性),或者 - 如果您在頁面上有jQuery - 請使用['$ .proxy'](http://api.jquery.com/jQuery.proxy/)。 –
好,太好了。這實際上是非常有用的信息 - 我的部門主管和網站訪問者有時會使用較舊的IE版本,原因是:\我會改寫'$ scope.addToList = $ .proxy(groceryInterface.addToList,$ scope)'? – LazerSharks