我想在表格中显示项目列表,并允许用户使用表单控件过滤项目。
我的问题
我可以在控制器首次执行时完成此操作,但是当我更改输入的值时,表不会使用正确的数据重新呈现。
我的问题
如何根据表单字段中的新值创建表格过滤器?
直播示例
http://plnkr.co/edit/7uLUzXbuGis42eoWJ006?p=preview
的Javascript
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.travelerFilter = 2;
$scope.groupFilter = "A";
$scope.records = [
{ leadName: "Jesse", travelerCount: 1, group: "A"},
{ leadName: "John", travelerCount: 1, group: "B"},
{ leadName: "James", travelerCount: 2, group: "A"},
{ leadName: "Bill", travelerCount: 2, group: "B"}
];
var travelerCountFilter = function(record) {
return record.travelerCount >= $scope.travelerFilter;
};
var groupFilter = function(record) {
return record.group === $scope.groupFilter;
};
$scope.filteredRecords = _.chain($scope.records)
.filter(travelerCountFilter)
.filter(groupFilter)
.value();
});
HTML
<!doctype html>
<html ng-app="plunker" >
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Show records with at least <input type="number" ng-model="travelerFilter" /> travelers.</p>
<p>Group <input type="text" ng-model="groupFilter" /></p>
<table>
<tr>
<th>Name</th>
<th>Count</th>
<th>Group</th>
</tr>
<tr ng-repeat="record in filteredRecords">
<td>{{record.leadName}}</td>
<td>{{record.travelerCount}}</td>
<td>{{record.group}}</td>
</tr>
</table>
</body>
</html>
答案 0 :(得分:3)
您可以将过滤器指定为ng-repeat的一部分,即:
<tr ng-repeat="record in records | filter:{group:groupFilter} | filter:{travelerCount:travelerFilter}">
请点击此处查看实时版本:http://plnkr.co/edit/1UcGDpwUAbtvEhUyCFss?p=preview
答案 1 :(得分:3)
angular可以自动双向绑定所有内容而无需过滤器:
<强> JS:强>
$scope.filteredRecords = function() {
return $scope.records.filter(function(record, i) {
return record.travelerCount === $scope.travelerFilter &&
record.group === $scope.groupFilter;
});
}
<强> HTML:强>
<tr ng-repeat="record in filteredRecords()">
请点击此处查看实时示例:http://plnkr.co/edit/aeBv2soGG06Trpp9WI4f?p=preview