多输入自定义 AngularJS 过滤器

Multi-Input Custom AngularJS Filter

我正在尝试构建自定义 Angular 过滤器。在我的示例代码中,它过滤了一个名称列表。过滤是通过 select 下拉菜单完成的,其中包含以下选项:

Contains
Equals
Starts with
Ends with
Does not contain

然后还有一个文本字段。文本字段将根据其前面的下拉列表中的内容充当搜索字段。最后,当您单击 'filter' 按钮时,过滤实际上发生了。 所以,如果我在文本字段中输入 'foo',然后在下拉列表中输入 select 'Ends with',然后单击 'filter',列表应该只显示条目以 'foo'.

结尾

你可以看到codepen here.

这是我的 HTML:

<div ng-app="programApp" ng-controller="programController">
  <label>Name: 
    <select ng-model="filterDropdown">
      <option>Contains</option>
      <option>Equals</option>
      <option>Starts with</option>
      <option>Ends with</option>
      <option>Does not contain</option>
    </select>
    <input ng-model="inputField" type="text">
  </label>
  <button ng-click="runFilter()">Filter</button>
  <ul>
    <li ng-repeat="name in names | filter:filterName(name, filterDropdown, filterSearch)">{{name.name}}, <i>{{name.age}}</i></li>
  </ul>
</div>

然后,这里是 Angular 过滤器(您可以在 the codepen 中找到更多 angular 代码,但没有其他的):

angular.module('programApp.filters', []).filter('filterName', function(){
    return function(entries, filterDropdown, filterInput) {
        //Each of these if statements should check which dropdown option is selected and return filtered elements accordingly.
        if(filterDropdown == 'Contains'){
            return entries.name.match(filterInput);
        }else if(filterDropdown == 'Equals'){
            return entries.name.match(filterInput);
        }else if(filterDropdown == 'Starts with'){
            if(entries.name.indexOf(filterInput) === 0){
                return entries;
            };
        }else if(filterDropdown == 'Ends with'){
            if(entries.name.indexOf(filterInput, entries.name.length - filterInput.length) !== -1){
                return entries;
            };
        }else if(filterDropdown == 'Does not contain'){
            return entries.name.match(!filterInput);
        };
    };
});

这是我的简单功能,当您单击 'filter' 时 运行s(意思是,当您在文本字段中键入时,它不会应用过滤器,直到您单击 'filter'按钮)。

$scope.runFilter = function(){
  $scope.filterSearch = $scope.inputField;
};

然而,当我 运行 它时,我没有得到错误,但过滤器实际上没有做任何事情。我的自定义过滤器有什么问题?

Codepen Here.

1) 您的 HTML 过滤器语法不正确。您不要将 filter 放在开头,因为它已经是一个名为 filter 的现有 Angular 过滤器。把你做的那个放上去。然后参数之间用冒号隔开,第一个参数是整个数组,不过是隐含的,你不写进去。

ng-repeat="thing in things | filterName:filterDropdown:filterSearch"

2) 您正在尝试访问每个条目的 属性,但您正在写入 entries.nameentries 是您的数组,而不是每个项目,因此您必须遍历它们。 Angular 有一个漂亮的 angular.forEach(array, function (item, index) {...}) 正是为了这个目的。

3) 您的过滤器需要 return 一个数组。在过滤器的开头实例化一个新数组,使用 forEach 遍历您的项目,如果该项目通过测试,将其添加到数组,然后 return 它。

Codepen