tina tina - 3 months ago 40
Javascript Question

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

I came across a problem when I try to pass param from ng-click to my function. I couldn't get my param. I am a new learner of Angular.js. So I think I may lack of basic understanding for ng-click inside ng-repeat. If anyone can help, I will be really appreciate it. Thank you.

View:

<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>


Controller:

(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);
})();


Route:

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


Console:
here

UPDATE:
Thanks for everyone's help. I am so new to developer's world, so it took me some time to learn JSfiddle and put my codes in there. Even though I add angular for external resource and also add angular for framework, I still couldn't let it work. But I still put fiddle here, if anyone think it's helpful. I modified my origin code a little bit.

JSfiddle1

Ted Ted
Answer

It looks like you need to use urCtrl.deleteRecipe(recipe.id) since you are using controller as and hence every time you refer to anything in your controller, you need to use the variable name you decided to use.

Take a look here for all the syntax details of controller as

UPDATE:

Ok, thanks for the JSFiddle! Just what we needed!

Here's the working JSFiddle

The only things wrong with the fiddle you had were:

1) You were referring to this when defining the recipes in your controller. ONLY refer to this when you are using the controller as syntax. Look above for further details.

2) You had a syntax error - you had };) instead of });

Other than that, your logic and AngularJS structure is fine, so nothing big :)

Let me know if something is still wrong!