membersound membersound - 5 months ago 16
AngularJS Question

How to filter ng-repeat by property value?

When iterating a list with

ng-repeat
, how can I add a condition/filter by a property of those items.

Example (of course there are several items in real world):

{"items":[{"type":"xxx"}]}


I only want to show the item where
type!='test'
.

The following just prints nothing:

<ul ng-repeat="item in items | filter: (item.type != 'test')">


Whereas if I remove the filter, all items are printed, of course.

Also, if possible, how could I create a condition that checks for multiple
type
values not being permitted?

Answer

Simple, use a function in the filter expression.

angular.module('app', [])
  .controller('AppCtrl', function($scope) {
    $scope.items = [{
      "type": "xxx"
    }, {
      "type": "test"
    }];

    $scope.filterFn = function(value) {
       return value.type !== 'test';
    };
  })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="AppCtrl">
  <ul>
    <li ng-repeat="item in items | filter: filterFn">{{item.type}}</li>
  </ul>
</div>

If your data schema changes just update the filter function.

You could also use object notation

angular.module('app', [])
  .controller('AppCtrl', function($scope) {
    $scope.items = [{
      "type": "xxx"
    }, {
      "type": "test"
    }];
  })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="AppCtrl">
  <ul>
    <li ng-repeat="item in items | filter: {type: '!test'}">{{item.type}}</li>
  </ul>
</div>

but this has some limitations like not suporting primitive value filters(it expects an object with properties as the item) and the same filter cannot be specified multiple times(something like {type:"!test!xxx"})

Comments