0

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 }}

KhoPhi
  • 9,660
  • 17
  • 77
  • 128
  • Possible duplicate of [How can I iterate over the keys, value in ng-repeat in angular](http://stackoverflow.com/questions/15127834/how-can-i-iterate-over-the-keys-value-in-ng-repeat-in-angular) – Durgpal Singh Sep 05 '16 at 13:26
  • @DurgpalSingh No, not duplicate. My question is, how to use the `key` in the first ng-repeat as filter for the second ng-repeat. The link you gave is how to do `(key, value) in dataset` – KhoPhi Sep 05 '16 at 13:33

1 Answers1

2

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>
Nikhilesh Shivarathri
  • 1,640
  • 10
  • 16
  • For my use case (in relation with `$firebaseArray`) I ended up doing `return value;` instead of `return { name: value }` Thank you – KhoPhi Sep 05 '16 at 14:11