gpt4 book ai didi

javascript - 如何将使用 $scope 的函数包含/注入(inject)到 angularjs 的 Controller 中?

转载 作者:可可西里 更新时间:2023-11-01 01:56:52 24 4
gpt4 key购买 nike

我正在尝试将工厂中保存的函数库包含到 Controller 中。类似于这样的问题: Creating common controller functions

我的主 Controller 是这样的:

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。我已将此工厂注入(inject)到上面的 Controller 中。

工厂

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
在 Object.factory.addToList
显然,我猜这与我在工厂内的函数中使用 $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;
});

关于javascript - 如何将使用 $scope 的函数包含/注入(inject)到 angularjs 的 Controller 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19642138/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com