angularjs

时间:2018-06-12 13:00:15

标签: javascript arrays angularjs filter ecmascript-6

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

我是以全名

完成的

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个字词。

  

此外,如果我输入正常字词india,那么我希望结果可以india过滤,就像我在代码段中所做的那样。怎么能这样做?

1 个答案:

答案 0 :(得分:2)

显然,您需要一个自定义过滤器。你的工作是将单词缩写为缩写。那么您可以简单地将模型与缩写相匹配,作为普通过滤器,我建议使用.indexOf()方法。

这是我的简单演示:

&#13;
&#13;
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'
  ];
});
&#13;
<!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>
&#13;
&#13;
&#13;

(示例区分大小写)