2

Suppose I have a table like this:

<tbody>
    <tr data-ng-repeat="object in objects">
        <td><input type="checkbox" value="{{object.id}}" data-ng-checked="object.checked" data-ng-mode="object.checked"/></td>
        <td>{{object.name}}</td>
        <td><a href="#" class="btn btn-default" data-ng-click="objectEdit()">Edit</a> <a href="#" class="btn btn-default">View</a></td>
    </tr>
</tbody>

What is the right way to have objectEdit notified which entry in objects is being referenced here?

Sorry, AngularJS newb.

2 Answers 2

8

Edit: created a demo on plunker.

You can use the expected behaviour like:

<a href="#" class="btn btn-default" data-ng-click="objectEdit(object)">Edit</a>

then in the scope have this method

$scope.objectEdit = function(item){
}

Or

without passing the object in the click function

<a href="#" class="btn btn-default" data-ng-click="objectEdit()">Edit</a>

and in the scope:

$scope.objectEdit = function(){
   this.item // access selected item
}

The property "item" on the called function context is always available, even if you pass the element to the function, so I would recommend not passing the object as parameter it is less verbose I guess.

Sign up to request clarification or add additional context in comments.

1 Comment

you will really have $scope.objectEdit, not just method in scope.
3

You can pass it into the function:

ng-click="objectEdit(object)"

To expand from my original answer (sorry was short because it was answered on my mobile), you can pass into your function the object in a loop. Also, and sometimes it makes more sense especially if you have an array, to pass in the index when you are looping over it in an ng-repeat:

ng-click="objectEdit($index)"

This allows us to splice or edit the element in the array:

$scope.objectEdit = function(i) {
   $scope.objects.splice(i,1);  // if we want to remove it in a delete function
   $scope.objects[i].name = 'new name';
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.