如何使用AngularJS根据ng-model过滤ng-repeat值
在这篇文章中,我们将看到如何使用AngularJS根据_ng-model指令来过滤_ng-repeat指令的值。
在AngularJS中可以根据ng-model过滤ng-repeat值,方法是将输入字段的值作为过滤器的表达式。我们可以在一个输入字段上设置ng-model指令来过滤ng-repeat值。下面的插图描述了实现的方法。
例子1:根据ng-model过滤输入文本ng-repeat值。这个过滤器将只显示匹配的城市的名字。
<!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>
HTML
输出: 示例2:根据ng-model.过滤输入文本ng-repeat值,这个过滤器在应用过滤器对每种语言进行大写后,将只显示匹配的编程语言的名称。
<!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>
HTML
输出: