Bir fabrikada tutulan işlev kitaplığını bir denetleyiciye dahil etmeye çalışıyorum. Bu gibi sorulara benzer : şöyle Creating common controller functions
Benim ana kontrolör:
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(); */
}
Sonra, başka bir .js dosyasında, ben fabrika groceryInterface oluşturduk. Bu fabrikayı yukarıdaki kontrolöre enjekte ettim.
Fabrika
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;
});
Ama konsolda ben Açıkçası ben bu ben içinde benim fonksiyonları $scope
kullanıyorum gerçeği ile ilgisi var tahmin ediyorum, vbReferenceError: $scope is not defined at Object.factory.addToList
almaya devam fabrika. Bunu nasıl çözebilirim? Baktığım diğer birçok örnekte, hiç kimse $scope
'u harici fabrika işlevlerinde kullanmıyor. Fabrikamda $scope
parametresini parametre olarak denedim, ancak bu düzlük işe yaramadı. (ör. recipeApp.factory('groceryInterface', function(){
)
Herhangi bir yardım gerçekten takdir edilmektedir!
Tatlı, teşekkürler. Bunu deneyeceğim! – LazerSharks
@Gnuey - 'bind''in IE'nin eski sürümlerinde mevcut olmadığını unutmayın. Bunları desteklemek ve ilk yöntemi kullanmak istiyorsanız, ya [bu MDN polyfill] kullanın (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind# Uyumluluk) veya - jQuery sayfanız varsa - bunun yerine ['$ .proxy'] (http://api.jquery.com/jQuery.proxy/) kullanın. –
Tamam, harika. Bu aslında son derece yararlı bilgiler - benim dept baş ve site ziyaretçileri bazı nedenlerle zaman zaman eski IE sürümleri kullanıyor: \ Bunun yerine $ scope.addToList = $ .proxy (bakeryInterface.addToList, $ scope) 'yazabilir miyim? – LazerSharks