Angular: ng-click参数是undefined,它在ng-repeat中

Angular: ng-click parameter is undefined, which is inside ng-repeat

本文关键字:它在 ng-repeat undefined ng-click 参数 Angular      更新时间:2023-09-26

当我试图从ng-click传递参数到我的函数时,我遇到了一个问题。我拿不到我的参数。我是一个刚学习Angular.js的人。所以我想我可能对ng-repeat里面的ng-click缺乏基本的理解。如果有人能帮忙,我将不胜感激。谢谢你。

视图:

<table>
  <tr ng-repeat="recipe in urCtrl.userRecipes | filter: {category: 'Grill'}">
    <td>{{ recipe.id }}</td>
    <td>{{ recipe.name }}</td>
    <td>{{ recipe.category}}</td>
    <td>{{ recipe.ingredients }}</td>
    <td>{{ recipe.instructions }}</td>
    <button ng-click="deleteRecipe(recipe.id)">Delete</button>
   </tr>
</table>

控制器:

(function userRecipeControllerIIFE() {
var UserRecipeController = function($scope, likeRecipesFactory, recipesFactory, appSettings) {
    function init() {
        ....
      $scope.deleteRecipe = function(data){
        console.log("this is recipe: ", data);
      };
    };
    init();
};
UserRecipeController.$inject = ['$scope', 'likeRecipesFactory', 'recipesFactory', 'appSettings'];
angular.module('recipesApp').controller('userRecipeController', UserRecipeController);
})();

路线:

$routeProvider.when('/user', {
            controller: 'userRecipeController as urCtrl',
            templateUrl: 'app/views/urView.html'
        })

控制台:

更新:谢谢大家的帮助。我对开发人员的世界是如此的陌生,所以我花了一些时间来学习JSfiddle并把我的代码放在那里。即使我为外部资源添加了angular,也为框架添加了angular,我仍然不能让它工作。但我还是把小提琴放在这里,如果有人觉得有用的话。我稍微修改了一下原始代码。

JSfiddle1

看起来您需要使用urCtrl.deleteRecipe(recipe.id),因为您正在使用controller as,因此每次您引用控制器中的任何内容时,您都需要使用您决定使用的变量名称

查看controller as

的所有语法细节

更新:

好的,谢谢你的JSFiddle!这正是我们需要的!

这是工作的JSFiddle

你的小提琴唯一的毛病是:

1)当你在控制器中定义配方时,你指的是this。当你使用controller as语法时,只引用this

2)你有一个语法错误-你有};)而不是});

除此之外,你的逻辑和AngularJS结构都很好,所以没什么大不了的:)

如果仍然有问题,请告诉我!

当使用controller as时,您可以将该方法放在控制器上:

var UserRecipeController = function($scope, likeRecipesFactory, recipesFactory, appSettings) {
    this.deleteRecipe = function(data){
        console.log("this is recipe: ", data);
    };
    function init() {
        ....
    };
    init();
};

然后在html

<button ng-click="urCtrl.deleteRecipe(recipe.id)">Delete</button>

我不认为这是导致你的问题,但你可能想要在TD标签中包装按钮,因为你可能会得到一些意想不到的布局问题。

<td><button ng-click="urCtrl.deleteRecipe(recipe.id)">Delete</button></td>

同样,这可能也不是导致你的问题,但正如其他人所建议的,你可能想传递整个"配方"。

<td><button ng-click="urCtrl.deleteRecipe(recipe)">Delete</button></td>

原因是,你的HTML实际上不需要知道你的控制器是如何删除一个食谱的。例如,如果您假设要更改应用程序,使配方具有delete()方法,则必须更改视图和控制器。如果您传递整个配方,您的视图将不需要任何更改。

请尝试使用ng-click="$parent.deleteRecipe(recipe.id)".

尝试替换

function init() {
        ....
      $scope.deleteRecipe = function(data){
        console.log("this is recipe: ", data);
      };
    };
    init();

var 
function init() {
}
init();
$scope.deleteRecipe = function(data){
    console.log("this is recipe: ", data);
};

$scope.init = function init(){
   return {
       deleteRecipe : function(id){ return data;}
   };
}

作为

 ng-click="init.deleteRecipe(id)"