Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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

share|improve this question
    
Simplest would be if you could already include the user name in the group json object together with the id on server side. – joni Jun 5 '14 at 19:14
    
on an angular solution, Im not sure whats the cleanest way.. maybe use a filter? – joni Jun 5 '14 at 19:15

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>
share|improve this answer

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>

Plunker

share|improve this answer

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.