Rufenstein Rufenstein - 16 days ago 7
AngularJS Question

AngularJS 1: Filtering objects in the child ng-repeat loop with a property of the parent object

I can't get an expression to work as a filter parameter.

I have two objects arrays

app.controller('MainCtrl', function($scope) {
$scope.name = 'World';

$scope.clients = [
{'client_id' : '1', 'client_name' : 'Anne'},
{'client_id' : '2', 'client_name' : 'Tim'},
{'client_id' : '3', 'client_name' : 'John'}
];

$scope.courses = [
{'ordered_by' : '1', 'course_name' : 'Marketing'},
{'ordered_by' : '1', 'course_name' : 'Project Management'},
{'ordered_by' : '1', 'course_name' : 'Analytics'},
{'ordered_by' : '2', 'course_name' : 'Big Data'},
{'ordered_by' : '2', 'course_name' : 'Data Visualization'},
{'ordered_by' : '3', 'course_name' : 'PHP'}
];
});


Looping through them with the ng-repeat directive works fine, but I would like to be able to filter the nested loop with a value of a property of an object that is currently processed by the parent loop.

The code that's below lists all courses for each person as I don't know how to pass the client_id value to the filter of the nested directive.

<body ng-controller="MainCtrl">
<p>Course list:</p>

<div ng-repeat="person in clients">
<strong><h2>{{person.client_name}} (ID: {{person.client_id}})</h2></strong>
<ul>

<!-- I wish it was this simple:
<li ng-repeat="course in courses | filter : {'ordered_by' : '{{person.client_id}}' }"> -->

<li ng-repeat="course in courses | filter : {'ordered_by' : '' }">
{{course.course_name}}<br><span>(Ordered by person with the ID: {{course.ordered_by}})</span>
</li>
</ul>

</div>


</body>


In the end output should be as follows:


Anne (ID: 1)


  • Marketing

  • Project Management

  • Analytics



Tim (ID: 2)


  • Big Data

  • Data Visualization



John (ID: 3)


  • PHP




I would like to know if it's possible to do it this way or which direction I should be looking at.

Would passing a value of the property be possible with a custom filter?
Can expressions be used as filter parameters?

Click here to see a working copy on Plunker

rrd rrd
Answer

Try this:

<div ng-repeat="person in clients">
  <strong><h2>{{person.client_name}} (ID: {{person.client_id}})</h2></strong>
  <ul>
    <li ng-repeat="course in courses">
      <span ng-if="person.client_id === course.ordered_by">
        {{course.course_name}}
      </span>
    </li>
  </ul>
</div>

I haven't tested it though.