我可以使用用户输入的字符动态过滤 Angular 的名称数组吗?

Can I dynamically filter an array of names with Angular with a user input character?

我目前正在研究我在此处找到的一些 Angular 示例 - https://code.angularjs.org/1.3.10/docs/guide/filter

我正在使用内置的 filterFilter 过滤器(嘿嘿),我读到我可能需要创建自己的过滤器(这样我就可以传递参数)但是如果过滤器只是重新运行。我正在研究的想法是尝试让用户定义用于过滤数组的字符。

我现在的代码是这样的:

var myApp = angular.module('FilterInControllerModule', [])
  .controller('FilterController', ['filterFilter', function(filterFilter) {
    this.filterChar = 'a';
    this.array = [
      {name: 'Tobias'},
      {name: 'John'},
      {name: 'Jack'},
      {name: 'Frank'},
      {name: 'Desmond'},
      {name: 'Allan'},
      {name: 'Margie'}
    ];
    this.filteredArray = filterFilter(this.array, this.filterChar);
  }]);  
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Filters Extended Example 1</title>
  </head>
  <body ng-app="FilterInControllerModule">
    <div ng-controller="FilterController as ctrl">
      Filter by character: <input ng-model="ctrl.filterChar" type="text" maxlength="1"><br><br>
      <div>
        All entries:
        <div ng-repeat="entry in ctrl.array">{{entry.name}}</div>
      </div><br>
      <div>
        Entries that contain an "{{ctrl.filterChar}}":
        <div ng-repeat="entry in ctrl.filteredArray">{{entry.name}}</div>
      </div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.min.js"></script>
    <script src="script.js"></script>
  </body>
</html>

如果您 运行 代码,您会发现模型和视图之间的双向绑定在控制器和表达式 {{ctrl.filterChar}} 之间起作用,但是控制器没有似乎重新评估实际过滤。为什么会这样?

您可以在控制器中使用 Array.filter()

  var myApp = angular.module('FilterInControllerModule', [])
   .controller('FilterController', ['filterFilter', function(filterFilter) {
      this.filterChar = 'a';
      this.array = [
        {name: 'Tobias'},
        {name: 'John'},
        {name: 'Jack'},
        {name: 'Frank'},
        {name: 'Desmond'},
        {name: 'Allan'},
        {name: 'Margie'}
      ];
      this.filterFilter = function() {
         return this.array.filter(function(element, index, sourceArray) {
              return element.name.indexOf(this.filterChar) !== -1;
         }.bind(this));
      }
   }]);  

出现此问题是因为您的函数 filterFilter 仅被求值一次。要重新评估它并在每个摘要循环中获取过滤后的数组,您可以这样做:

在你的控制器中,使用函数:

var that = this;
this.filterMyArray = function() {
    return filterFilter(that.array, that.filterChar);
}

...在你的 html

<div ng-repeat="entry in ctrl.filterMyArray()">{{entry.name}}</div>