Reputation: 1800
I am trying to get the item of array on click when I am working with the reverse array. but getting the wrong index values.
when I clicked on `[7] Sebastian who is 50 years old
<button ng-click="show_id($index)">get my id</button>
I want alert value should be 7 not 0 but it alerts 0
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.1/angular.min.js"></script>
<script>
angular.module("my_app",[])
.controller("my_ctr",function($scope){
$scope.show_id=function(index){
alert(index);
}
})
</script>
</head>
<body ng-app="my_app" ng-controller="my_ctr">
<div ng-init="friends = [
{id:1, name:'John', age:25, gender:'boy'},
{id:2, name:'Jessie', age:30, gender:'girl'},
{id:3, name:'Johanna', age:28, gender:'girl'},
{id:4, name:'Joy', age:15, gender:'girl'},
{id:5, name:'Mary', age:28, gender:'girl'},
{id:6, name:'Peter', age:95, gender:'boy'},
{id:7, name:'Sebastian', age:50, gender:'boy'},
]">
I have {{friends.length}} friends. They are:
<ul>
<li ng-repeat="friend in friends.slice().reverse() ">
[{{friend.id}}] {{friend.name}} who is {{friend.age}} years old.
<button ng-click="show_id($index)">get my id</button>
</li>
</ul>
</div>
</body>
</html>
I want to do edit and update that particular record how can I do that?
Upvotes: 0
Views: 108
Reputation: 801
As you are iterating on the reverse of the list, you cannot get the index of original list
to get that you need to use the below
ng-click="show_id(friends.length-$index)"
Upvotes: -1
Reputation: 72849
Since you're looking for the id
of the "current friend", just use the id
provided in your object:
Replace:
<button ng-click="show_id($index)">get my id</button>
With:
<button ng-click="show_id(friend.id)">get my id</button>
Upvotes: 2