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 = '';
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With