可编辑的AngularJS输入过滤器

时间:2015-05-07 17:03:24

标签: javascript html angularjs filter angularjs-filter

我有一个对象数组加载到ng重复列表中。当用户单击“过滤器”按钮时,该列表将根据在其正上方的输入字段中输入的值进行过滤。这很好。但是,我还想在输入旁边选择一个下拉菜单来编辑输入过滤器的效果。

换句话说,过滤器处理输入字段中值的方式应根据在其旁边的下拉列表中选择的选项进行更改。

以下是代码:

HTML:

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

角:

angular.module('programApp', [
    'programApp.controllers',
]);
angular.module('programApp.controllers', [])
    .controller('programController', ['$scope', '$filter', '$http', 
    function($scope, $filter, $http){

      $scope.names = [{
            'name':'Fred',
            'age':'35 years'
        },{
            'name':'Alberta',
            'age':'46 years'
        },{
            'name':'Francis',
            'age':'31 years'
        },{
            'name':'Sarah',
            'age':'12 years'
        },{
            'name':'Matthew',
            'age':'16 years'
        },{
            'name':'Tracy',
            'age':'87 years'
        },{
            'name':'Jordan',
            'age':'35 years'
        },{
            'name':'Sam',
            'age':'26 years'
        },{
            'name':'Mason',
            'age':'38 years'
        },{
            'name':'Travis',
            'age':'11 years'
        },{
            'name':'Corey',
            'age': '86 years'
        },{
            'name':'Andrew',
            'age':'55 years'
        },{
            'name':'John',
            'age':'66 years'
        },{
            'name':'Jack',
            'age':'73 years'
        }];

      $scope.runFilter = function(){
        $scope.filterNameField = $scope.nameField;
      };

    }]);

因此,如果选择Starts with,我希望输入按start with进行过滤,如果选择equals,则只显示与输入完全匹配的结果,依此类推与其他选项。我该怎么做?

查看等效的Codepen here

2 个答案:

答案 0 :(得分:1)

您必须创建自己的$过滤器并按照您希望的方式过滤它:

HTML:

<li ng-repeat="name in names | myFilter:filterNameField:filterType">{{name.name}}, <i>{{name.age}}</i></li>

Javascript:

.$filter(function(){
    return function(input, name, type){
        //return based on name/type
    }
});

答案 1 :(得分:0)

对于严格的比较,您可以在html中使用过滤器:

{{filterExpression | filter: stringToCompare: true}}

首先,你需要做一个像这样的函数:

function(array,stringToCompare){
  if(array.startWith(stringToCompare) ==true) 
      Return whatYouNeed
};