Filters are not just limited to manipulating text output of Angular expressions - they can also be used to intelligently sort lists repeated by ng-repeat. For example, wouldn't it be great if we could filter the items in the people
scope object below based on a search string?
function TestCtrl() {
var self = this;
self.people = [
{
name: "Eric Simons",
born: "Chicago"
},
{
name: "Albert Pai",
born: "Taiwan"
},
{
name: "Matthew Greenster",
born: "Virginia"
}
];
}
angular.module('app', [])
.controller('TestCtrl', TestCtrl);
To search across the people
scope array, we just need to pass along the search
scope variable (being populated by the input below) into the ng-repeat filter:
<body ng-app="app" ng-controller="TestCtrl as test">
<input type="text" ng-model="search" />
<p ng-repeat="person in test.people | filter: search">
{{ person.name }}
</p>
</body>
By default, this will search all attributes in the people objects (currently that includes name
and born
). You can have it search specific attributes by dotting the field name in the model like so:
<input type="text" ng-model="search.name" />
For a general search across all attributes, you can simply use $:
<input type="text" ng-model="search.$" />