如何将使用$ scope的函数包含/注入到angularjs的控制器中?

我正在尝试将工厂中保存的函数库包含在控制器中。

我的 如下所示:

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文件中,我创建了工厂杂货接口。我已经将此工厂注入到上面的控制器中。

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;

});

显然,我猜这与$scope我在工厂中的函数中使用的事实有关。我该如何解决?我注意到在我看过的许多其他示例中,没有人$scope在其外部工厂功能中使用过。我曾尝试$scope在工厂中将inject作为参数注入,但这种方法显然行不通。(例如recipeApp.factory('groceryInterface', function(){

任何帮助,我们都感激不尽!

回答:

您的工厂不在$scope同一范围内,因此您无法访问您的。

尝试以下方法:

recipeApp.controller('recipeController', function ($scope, groceryInterface) {

$scope.addToList = groceryInterface.addToList;

$scope.clearList = groceryInterface.clearList;

$scope.add = groceryInterface.add;

$scope.addUp = groceryInterface.addUp;

}

recipeApp.factory('groceryInterface', function () {

var factory = {};

factory.addToList = function (recipe) {

this.groceryList.push(recipe);

}

factory.clearList = function() {

var last = this.prevIngredients.pop();

}

});


另外,您可以尝试使用一种更加面向对象的方法:

recipeApp.controller('recipeController', function ($scope, groceryInterface) {

$scope.groceryFunc = new groceryInterface($scope);

}

recipeApp.factory('groceryInterface', function () {

function Factory ($scope) {

this.$scope = $scope;

}

Factory.prototype.addToList = function (recipe) {

this.$scope.groceryList.push(recipe);

}

Factory.prototype.clearList = function() {

var last = this.$scope.prevIngredients.pop();

}

return Factory;

});

以上是 如何将使用$ scope的函数包含/注入到angularjs的控制器中? 的全部内容, 来源链接: utcz.com/qa/403717.html

回到顶部