AngularJS:使用select和input过滤记录

时间:2016-09-27 13:35:59

标签: angularjs

我在使用输入和过滤器参数过滤记录方面遇到一些问题,我从select中选择。我看到了很好的例子:angular.js select filter type of input box
但是当我尝试使用ng-options进行选择时,它全部崩溃了。我的错是什么?

HTML

<select ng-model="filter" ng-options="item.key for item in param track by item.value">      
</select>
<input ng-model="query" />
<ul>
   <li ng-repeat="person in persons | filter: getFilter()"> firstname: {{person.firstname}}, lastname: {{person.lastname}}
   </li>
</ul>


JS

  $scope.persons = [
      {firstname: 'Tom', lastname: 'Mann'},
      {firstname: 'Gil', lastname: 'Jeff'},
      {firstname: 'Kit', lastname: 'Tio'}
  ];

  $scope.param = [
    {value: 'firstname', key: 'First Name'},
    {value: 'lastname', key: 'Last Name'}
    ];

  $scope.filter = $scope.param[0];          

  $scope.getFilter = function() {
      var filter = {};
      filter[$scope.filter] = $scope.query;
      return filter;
  };

http://plnkr.co/edit/L6lSuF2S249d5pDsKEx9?p=preview

1 个答案:

答案 0 :(得分:2)

由于ng-model的注释,select ng-options导致了一个对象。

将您的getFilter功能更改为此功能,它应该有效:

$scope.getFilter = function() {
    var filter = {};
    // $scope.filter is equal to {value: 'firstname', key: 'First Name'}
    filter[$scope.filter.value] = $scope.query;
    return filter;
};

请参阅this fixed plunker

解决此问题的另一种方法是更改​​ng-options中的符号:

ng-options="item.value as item.key for item in param track by item.value"