0

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

2
  • Simplest would be if you could already include the user name in the group json object together with the id on server side. Commented Jun 5, 2014 at 19:14
  • on an angular solution, Im not sure whats the cleanest way.. maybe use a filter? Commented Jun 5, 2014 at 19:15

3 Answers 3

1

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>
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

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.