【发布时间】:2017-10-09 19:49:47
【问题描述】:
我正在尝试制作一个过滤表,以仅显示包含搜索框中任何字符串的行。我有一个简单的例子,我只是想根据w3schools tutorial 开始工作: https://www.w3schools.com/angular/tryit.asp?filename=try_ng_tables_css
这是我的过滤器
<tr ng-repeat="x in names | filter:searchKeyword">
它看起来与 API 参考中给出的示例非常相似:<tr ng-repeat="friend in friends | filter:searchText">
https://docs.angularjs.org/api/ng/filter/filter
问题是当我在搜索框中输入内容时没有任何反应。我希望表格随着搜索词的变化而动态变化。我错过了什么?
这是我的代码:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body>
<label>Search: <input type="text" ng-model="searchKeyword"></label>
<div ng-app="myApp" ng-controller="customersCtrl">
<table>
<tr ng-repeat="x in names | filter:searchKeyword">
<td>{{ x.Name }}</td>
<td>{{ x.Country }}</td>
<td>{{ x.City }} </td>
</tr>
</table>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope) {
$scope.names = [
{"Name":"Alfreds Futterkiste","City":"Berlin","Country":"Germany"},
{"Name":"Ana Trujillo Emparedados y helados","City":"México D.F.","Country":"Mexico"},
{"Name":"Antonio Moreno Taquería","City":"México D.F.","Country":"Mexico"},
{"Name":"Around the Horn","City":"London","Country":"UK"},
{"Name":"B's Beverages","City":"London","Country":"UK"},
{"Name":"Berglunds snabbköp","City":"Luleå","Country":"Sweden"},
{"Name":"Blauer See Delikatessen","City":"Mannheim","Country":"Germany"},
{"Name":"Blondel père et fils","City":"Strasbourg","Country":"France"},
{"Name":"Bólido Comidas preparadas","City":"Madrid","Country":"Spain"},
{"Name":"Bon app'","City":"Marseille","Country":"France"},
{"Name":"Bottom-Dollar Marketse","City":"Tsawassen","Country":"Canada"},
{"Name":"Cactus Comidas para llevar","City":"Buenos Aires","Country":"Argentina"},
{"Name":"Centro comercial Moctezuma","City":"México D.F.","Country":"Mexico"},
{"Name":"Chop-suey Chinese","City":"Bern","Country":"Switzerland"},
{"Name":"Comércio Mineiro","City":"São Paulo","Country":"Brazil"}
];
});
</script>
</body>
</html>
【问题讨论】:
-
您只需将输入框放入您的应用程序中即可:) 参见演示:jsfiddle.net/wbp3s95q
-
另外,DOM 过滤器很糟糕(将
$filter注入到您的控制器中)。看看为什么:toddmotto.com/… -
谢谢!那解决了它。另外,感谢您的参考。我一定会学习如何提高过滤此类内容的性能。
-
我建议@sh0ber 添加他们的评论作为答案,以便可以结束并关闭。
-
@Phix 你去!
标签: javascript html angularjs angularjs-directive angular-filters