2

我想在表格中显示项目列表,并允许用户使用表单控件过滤项目。

我的问题
我能够在控制器首次执行时完成此操作,但是当我更改输入的值时,表格不会使用正确的数据重新呈现。

我的问题
如何根据表单字段中的新值制作表格过滤器?

现场示例
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>
4

2 回答 2

3

您可以将过滤器指定为 ng-repeat 的一部分,即:

<tr ng-repeat="record in records | filter:{group:groupFilter} | filter:{travelerCount:travelerFilter}">

在这里查看实时版本:http ://plnkr.co/edit/1UcGDpwUAbtvEhUyCFss?p=preview

于 2013-04-08T17:52:22.833 回答
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

于 2013-04-08T19:48:23.840 回答