How to filter ng-repeat values according to ng-model using AngularJS ?
In this article, we will see how to filter the value of the ng-repeat directive according to the ng-model directive using AngularJS.
The ng-repeat values can be filtered according to the ng-model in AngularJS by using the value of the input field as an expression in a filter. We can set the ng-model directive on an input field to filter ng-repeat values. The below illustrations describes the approach for the implementation.
Example 1: Filtering input text ng-repeat values according to ng-model. This filter will show the names of only the matching city.
<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
</head>
<body>
<center>
<h1 style="color:green;">
GeeksforGeeks
</h1>
<h3>
Filter ng-repeat values according to ng-model
</h3>
</center>
<div ng-app="app1" ng-controller="controller1">
<p>Type a city name in the input field:</p>
<p>
<input type="text" ng-model="testfilter">
</p>
<p>Filter show the names of only the matching city.</p>
<ul>
<li ng-repeat="x in citynames | filter:testfilter">
{{ x }}
</li>
</ul>
</div>
<script>
angular.module('app1', []).controller(
'controller1', function($scope) {
$scope.citynames = [
'Ahmedabad',
'Ajmer',
'Bhopal',
'Jaipur',
'Surat',
'Nagpur',
'Mumbai',
'Pune',
'Indore',
'Udaipur',
'Jodhpur',
'Jabalpur',
'Gwalior',
'Delhi',
'Lucknow',
'Banglore'
];
});
</script>
</body>
</html>
Output: Example 2: Filtering input text ng-repeat values according to ng-model. This filter will show the names of only the matching programming language after capitalizing on each language by applying the filter.
<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
</head>
<body>
<center>
<h1 style="color:green;">
GeeksforGeeks
</h1>
<h3>
Filtering input text ng-repeat
values according to ng-model
</h3>
</center>
<div ng-app="app1" ng-controller="controller1">
<p>
Type a programming language
name in the input field:
</p>
<p>
<input type="text" ng-model="testfilter">
</p>
<p>
Filter shows the names of only the
matching programming language after
capitalizing each language by
applying filter.
</p>
<ul>
<li ng-repeat=
"x in programminglanguagenames| filter:testfilter">
{{ x |myfilter}}
</li>
</ul>
</div>
<script>
var app = angular.module('app1', []);
app.filter('myfilter', function () {
return function (x) {
var i, c, txt = "";
for (i = 0; i < x.length; i++) {
c = x[i];
c = c.toUpperCase();
txt += c;
}
return txt;
};
});
app.controller('controller1', function ($scope) {
$scope.programminglanguagenames = [
'cobol',
'pascal',
'ruby',
'php',
'perl',
'python',
'c',
'c++',
'java',
'html',
'css',
'javascript',
'basic',
'lisp',
'smalltalk',
'bootstrap'
];
});
</script>
</body>
</html>
Output: