0

我想创建一个可以按短名称和全名过滤的过滤器

我用全名做了

angular.module('myApp', []).controller('namesCtrl', function($scope) {
    $scope.names = [
        'Indian Overseas Bank',
        'Housing Development Finance Corporation',
        'Industrial Credit and Investment Corporation of India',
        'Indian Bank',
        'City Bank',
        'City Union Bank',
        'Kotak Mahindra Bank',
        'Tamilnadu Mercantile Bank ',
        'State Bank Of India'
    ];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>

<div ng-app="myApp" ng-controller="namesCtrl">

<p>Type a letter in the input field:</p>

<p><input type="text" ng-model="test"></p>

<ul>
  <li ng-repeat="x in names | filter:test">
    {{ x }}
  </li>
</ul>

</div>

但我不确定,如何按短名称过滤IOB, HDFC, SBI

我希望结果像

Filter word     : Expected result 

IOB             : Indian Overseas Bank 
HDFC            : Housing Development Finance Corporation
SBI             : Stete Bank of India
ICICI           : Industrial Credit and Investment Corporation of India'

注意:这些银行是印度银行。看,当我过滤时过滤 SBI and ICICI器将无法识别of, and单词。

此外,如果我输入普通的单词 like india,那么我希望结果会india像我在片段中所做的那样被过滤。怎么能这样?

4

1 回答 1

3

显然,您需要一个自定义过滤器。你的工作是将单词分解成缩写。然后你可以简单地将模型与你的缩写匹配,就像一个普通的过滤器一样,我建议的.indexOf()方法。

这是我的简单演示:

var app = angular.module('myApp', []);
app.filter('myFilter', function() {
  return function(inp, model) {
    if (!model) {
      return inp;
    }
    var ignore = ["of", "and", "Of", "And"];
    var array = [];
    for (var i = 0; i < inp.length; i++) {
      var str = "";
      var arr = inp[i].split(" ");
      for (var j = 0; j < arr.length; j++) {
        if (ignore.indexOf(arr[j]) == -1) {
          str += arr[j][0];
        }
      }
      // str = str.toLowerCase();
      // model = model.toLowerCase();
      if (str.indexOf(model) != -1) {
        array.push(inp[i]);
      }
    }
    return array;
  };
});
app.controller('namesCtrl', function($scope) {
  $scope.names = [
    'Indian Overseas Bank',
    'Housing Development Finance Corporation',
    'Industrial Credit and Investment Corporation of India',
    'Indian Bank',
    'City Bank',
    'City Union Bank',
    'Kotak Mahindra Bank',
    'Tamilnadu Mercantile Bank ',
    'State Bank Of India'
  ];
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

  <div ng-app="myApp" ng-controller="namesCtrl">

    <p>Type a letter in the input field:</p>

    <p><input type="text" ng-model="test"></p>

    <ul>
      <li ng-repeat="x in names | myFilter:test">
        {{ x }}
      </li>
    </ul>

  </div>

</body>

</html>

(示例区分大小写)

于 2018-06-12T13:19:09.407 回答