Filter an array of objects by attribute with integer value in ng-repeat

I have such a directive

ng-repeat="place in tb_places | filter:{'id':inputID}" 

to output some array of objects it looks like this:

 $scope.tb_places = [ {name: 'some1', id:1} ... {name: 'some10', id:10} {name: 'some11', id:11} {name: 'some12', id:12} ... ] 

when I change the input identifier and set it to 1, the result array fills the elements of the original array with "identifiers" 1 and 10, 11, 12. Thus, part of the "id" value is checked as substrings, not numbers. How can I cure him?

thanks!

UPD I tried to add the expression ": true" in the filter expression - it completely clears the output (array of results), it works for a simple array of strings, but not for objects ("true" wants an exact match with the template object, this means that all of it properties)

SOLVE!!!

Sorry guys, I'm to blame! "inputID" was not the same type as "id" (string vs int), so the built-in comparator (": true") returns false. Many thanks!

ps sorry, I can not vote for you answers - lack of reputation ... see you!

+7
arrays angularjs angularjs-filter angularjs-ng-repeat
source share
3 answers

You need to add comparator according to angular filter to achieve your requirement.

Can you change the code as:

 ng-repeat="place in tb_places | filter: {'id' : inputID} : true" 
+5
source share

You need to either put your own comparator or manually convert the requested value to an integer and use the true flag:

Controller:

 app.controller('DemoCtrl', function() { this.query = '1'; this.queryAsInt = function() { return parseInt(this.query, 10); }; this.stuff = [ {id: 1, label: 'Foobar 1'}, {id: 2, label: 'Foobar 2'}, {id: 3, label: 'Foobar 3'}, {id: 4, label: 'Foobar 4'}, {id: 5, label: 'Foobar 5'}, {id: 6, label: 'Foobar 6'}, {id: 7, label: 'Foobar 7'}, {id: 8, label: 'Foobar 8'}, {id: 9, label: 'Foobar 9'}, {id: 10, label: 'Foobar 10'}, {id: 11, label: 'Foobar 11'}, {id: 11, label: 'Foobar 12'} ]; this.compare = function(a, b) { return parseInt(a, 10) === parseInt(b, 10); }; }); 

View:

 <div ng-controller="DemoCtrl as demo"> <input ng-model="demo.query"> <p>With custom comparator:</p> <ul> <li ng-repeat="item in demo.stuff | filter:{id:demo.query}:demo.compare"> {{item.label}} </li> </ul> <p>With type casting:</p> <ul> <li ng-repeat="item in demo.stuff | filter:{id:demo.queryAsInt()}:true"> {{item.label}} </li> </ul> </div>); 

And here is an example: http://jsbin.com/kecihexeyu/1/edit?html,js,output

+1
source share

Write your own comparator.

HTML

 <li ng-repeat="place in tb_places | filter:{'id':inputID}: filterId">{{place.id}}</li> 

Javascript

 filterId = function(actual, expected) { return actual == expected; } 

Full version of Plunker. http://plnkr.co/edit/3JEvThiemq8ro8cXCYBd?p=preview

+1
source share

All Articles