【问题标题】:Angularjs Filter search starting with given textAngularjs过滤器搜索从给定文本开始
【发布时间】:2018-07-10 05:03:43
【问题描述】:

我有以下 html 代码:

  <p><input type="text" ng-model="test"></p>
  <ul>
   <li ng-repeat="x in names | filter:test">
    {{ x }}
   </li>
  </ul>

对应的JS是:

<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
    $scope.names = [
        'Jabi',
        'Cabi',
        'Margareth',
        'Hege',
        'Joe',
        'Gustav',
        'Birgit',
        'Mary',
        'Kai'
    ];
});
</script>

问题是当我输入“bi”时,过滤器会返回所有包含“bi”的名称,但是我希望过滤器应该只返回以“bi”开头的名称(或者 watever 写在输入文本框中)

【问题讨论】:

标签: javascript jquery angularjs


【解决方案1】:

由于您只需要匹配的大小写/字母,因此您必须创建一个自定义过滤器,如下所示,

演示

angular.module('myApp', []).controller('namesCtrl', function($scope) {
    $scope.names = [
        'Jabi',
        'Cabi',
        'Margareth',
        'Hege',
        'Joe',
        'Gustav',
        'Birgit',
        'Mary',
        'Kai'
    ];
    
$scope.onlyMatch = function (input, output) {
    var Str = (input + "").toLowerCase();
    return Str.indexOf(output.toLowerCase()) === 0;
}

 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="namesCtrl">
<p><input type="text" ng-model="test"></p>
  <ul>
   <li ng-repeat="x in names |  filter:test:onlyMatch">
    {{ x }}
   </li>
  </ul>
  </body>

【讨论】:

  • 这不符合我的要求。如果我输入“bi”,我只需要显示“Birgit”。 . .任何帮助?
猜你喜欢
  • 2018-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-12
  • 1970-01-01
  • 1970-01-01
  • 2015-10-02
  • 2015-04-19
相关资源
最近更新 更多