Reputation: 1
I have the following response from a service in my AngularJS app:
{
"people": [
{"id": "b3b38689", "name": "Tom"},
{"id": "a62e603f", "name": "Dick"},
{"id": "da703c62", "name": "Harry"}
],
"groups": [
{"name": "group 1", participants: ["b3b38689", "a62e603f"]},
{"name": "group 2", participants: ["a62e603f", "da703c62"]}
]
}
Ultimately this gets mapped to
$scope.data
Then, in my view I have:
<div data-ng-repeat="group in data.groups">
<h1>{{group.name}}</h1>
<p data-ng-repeat="participant in group.participants">...</p>
</div>
This is successfully outputting:
<div>
<h1>group 1</h1>
<p>...</p>
<p>...</p>
</div>
<div>
<h1>group 2</h1>
<p>...</p>
<p>...</p>
</div>
I'd like to put into the 'p' tags "people[n].name" of the entry that the id matches up.
Is anyone able to help me understand how I would accomplish this please?
Regards,
Chris
Upvotes: 0
Views: 3145
Reputation: 961
You can use filter as below:
<p data-ng-repeat="participant in group.participants">
{{(data.people | filter:search(participant))[0].name}}
</p>
javascript:
$scope.search = function(name){
return function(item)
{
return item.id == name;
}
};
Here is the plunker link:
http://plnkr.co/edit/oaHIw1c8U6l8YYIsaGfo?p=preview
Upvotes: 0
Reputation: 5290
Filter data.people
by the participant id:
<p data-ng-repeat="participant in group.participants">
<span ng-bind="(data.people | filter:{id:participant})[0].name"></span>
</p>
Upvotes: 1
Reputation: 18513
You need a way to lookup someone based on their id. There are lots of ways to do this but one way would be to convert your people array into an object where the id field are keys. e.g.
$scope.people = {};
var peopleArray = $scope.data.people;
for (var i = 0; i < $scope.data.people.length; i++) {
$scope.people[peopleArray[i].key] = peopleArray[i].name;
}
Then in your html you can do
<p>{{people[participant]}}</p>
Upvotes: 1