Reputation: 23
I have a simple array of objects {name,age}
(see my jsfiddle). I use an ng-repeat to print all the names and I would like to print, outside the ng-repeat loop, the age of the name on which I click.
<body ng-app="myapp">
<div ng-controller="MyController" >
<ul>
<li ng-repeat="friend in myData.friends" ng-click="myData.doClick($index)">{{friend.name}}</li>
</ul>
<p>Age :</p>
<p>{{}}</p>
</div>
<script>
angular.module("myapp", []).controller("MyController", function($scope) {
$scope.myData = {};
$scope.myData.friends = [{ name: "Al",age:26}, { name: "Mike",age:21}, { name: "Brian",age:46} ];
$scope.myData.doClick = function(item) {
}
} );
</script>
</body>
Upvotes: 2
Views: 1209
Reputation: 1
The below code should work for you....
<body ng-app="myapp">
<div ng-controller="MyController" >
<ul>
<li ng-repeat="friend in myData.friends" ng-click="myData.doClick(friend.name)">{{friend.name}}</li>
</ul>
<p>Age :</p>
<p>{{ageval}}</p>
</div>
<script>
angular.module("myapp", []).controller("MyController", function($scope) {
$scope.myData = {};
$scope.myData.friends = [{ name: "Al",age:26}, { name: "Mike",age:21}, { name: "Brian",age:46} ];
$scope.myData.doClick = function(item) {
for (i = 0; i < $scope.myData.friends.length; i++) {
if (item == $scope.myData.friends[i]["name"]) {
$scope.ageval = $scope.myData.friends[i]["age"];
}
}
}
} );
</script>
</body>
Upvotes: 0
Reputation: 3411
Instead of passing the $index
, you should pass the object itself, friend
, then you can read his information.
Quick refactoring: http://jsfiddle.net/par2nrd4/4/
Upvotes: 1