0

I have 2 scope. I want to find based on the id of the scope "country", the country's name.

How can I print "France" for John, in this example.

$scope.country = [
{id:"1",name:"France"},
{id:"2",name:"Spain"}

];

$scope.people = [
{name:"John",country:"1"},
{name:"Ben",country:"2"}

]

I tried :

<tr ng-repeat="k in people">
<td>{{k.name}}</td>
<td>{{country | filter : {"id" : k.country } }}</td>

</tr>

I dont know if I am doit it wrong or not, but I can only get the array, not the field name of the country.

3 Answers 3

2

Try like this.

var app = angular.module('anApp', []);
app.controller('ctrl', function($scope) {
  $scope.country = [{
      id: "1",
      name: "France"
    },
    {
      id: "2",
      name: "Spain"
    }

  ];

  $scope.people = [{
      name: "John",
      country: "1"
    },
    {
      name: "Ben",
      country: "2"
    }

  ]

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.min.js"></script>

<div ng-app="anApp" ng-controller="ctrl">
  <div class="form-group">
    <table>
      <tr ng-repeat="k in people">
        <td>{{k.name}}</td>
        <td ng-repeat="c in country | filter:{id:k.country}">{{c.name}}</td>

      </tr>
    </table>
  </div>
</div>

Sign up to request clarification or add additional context in comments.

5 Comments

This is the smartest of the answers imo because it handles the case where there is no corresponding country
That's really smart.
@CameronRodriguez not really because there will be a missing <td> if filter returns empty array.
Agreed, it shouldn't be on the td, it should be inside it so that it will show regardless. I meant it won't throw an exception
@CameronRodriguez angular catches exceptions in expressions....won't get thrown. Can prove this in my plunker example by removing country or changing id
1

Can set filter up this way:

<td>{{(country | filter : {"id" : k.country })[0].name }}</td>

DEMO

1 Comment

That's just great. Thanks for your help.
0

In my opinion, generally speaking, if you want to share or access data between different scopes, you have to use the rootScope, but I recommend you to always use services if you need to share some data between scopes.

So I think it's a matter of application design not how to implement this requirement in AngularJS.

Hope this could help you

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.