Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-repeat and filtering array of primitives in angular

What I want to do is to filter an array of number/string items by an input value. My code is something like this.

It works well if $scope.groups[#].numbers is an array of objects, the filter search through the properties of the objects. However I want to filter my simple array of simple values in the case is being tracked by $index.

Is that possible? any workaround on this? or I need to use an array of object anyway.

Here a version of my example on jsfiddle http://jsfiddle.net/u9y9h/3/

html:

<div ng-app>
<div ng-controller="repeater">
  <input placeholder="number" type="text" ng-model="number">
  <input type="button" ng-click="addItem()" value="Add item"><br>
  <input placeholder="query"  type="text" ng-model="query">
  <div ng-repeat="group in groups">
    <h3>{{group.title}}</h3>
    <ul>
      <li ng-repeat="item in group.numbers track by $index | filter:query">{{item}}</li>
    </ul>      
  </div>
</div>
</div>

js:

function repeater($scope) {
  $scope.items = [];
  $scope.groups = [{
    title: 'even',
    numbers: []
  }, {
    title: 'odd',
    numbers: []
  }];

  $scope.addItem = function () {
    if ($scope.number % 2 == 0) {
      $scope.groups[0].numbers.push($scope.number);
    } else {
      $scope.groups[1].numbers.push($scope.number);
    }
    $scope.number = '';
  }
}
like image 610
asumaran Avatar asked Jan 12 '23 18:01

asumaran


1 Answers

The track by should come after the filter as in this example from the angular docs:

item in items | filter:searchText track by item.id is a pattern that might be used to apply a filter to items in conjunction with a tracking expression.

So switch

<li ng-repeat="item in group.numbers track by $index | filter:query">

to

<li ng-repeat="item in group.numbers | filter:query track by $index ">{{item}}</li>

And you're set.

Updated fiddle

like image 86
KayakDave Avatar answered Jan 22 '23 06:01

KayakDave