Rexford Rexford - 2 months ago 17
Javascript Question

Filter ng-repeat with key from parent ng-repeat

I have this:

<div class="row" ng-repeat="(key, value) in categories">
<h5>{{ value }}</h5>
<ul>
<li ng-repeat="post in $parent.posts | filter: key">{{ post.name }} -- {{ post.category }}</li>
</ul>
</div>


I want the nested
ng-repeat
of the post be to filtered by the category
key
.

The idea is to have each post displaying related posts, where
{{ post.category }}
is same as
{{ value }}

Answer

That requirement to iterate over object and to filter the child ng-repeat using the key of parent can be achieved by using a custom function which in turn returns the object. Check the sample application created below.

var app = angular.module('sample', []);

app.controller('samplecontroller', function($scope) {

  $scope.filterKey = function(value) {
    return {
      name: value
    };
  };

  $scope.categories = {
    'John': 'English'
  };
  $scope.posts = [{
    name: 'John',
    category: 'General'
  }, {
    name: 'James',
    category: 'Restricted'
  }]
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="sample">
  <div ng-controller="samplecontroller">
    <div class="row" ng-repeat="(key, value) in categories">
      <h5>{{ value }}</h5>
      <ul>
        <li ng-repeat="post in $parent.posts | filter: filterKey(key)">{{ post.name }} -- {{ post.category }}</li>
      </ul>
    </div>
  </div>

</body>

Comments