jQuery Angular JS 'Startswith' 自定义过滤器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19501300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:06:58  来源:igfitidea点击:

Angular JS 'Startswith' custom filter

javascriptjqueryangularjsfilterstartswith

提问by Chris Pena

So I've been trying a while to make a custom filter that searches for the 'Startswith' parameters rather than the 'Contains'. Every filter that I've written haven't seem to work properly. Here is an example of what I'm trying to achieve ---> http://jsfiddle.net/DMSChris/9ptr9/

所以我一直在尝试制作一个自定义过滤器来搜索“Startswith”参数而不是“Contains”。我编写的每个过滤器似乎都无法正常工作。这是我试图实现的一个例子---> http://jsfiddle.net/DMSChris/9ptr9/

function FilterCtrl() {
var scope = this;
scope.doFilter = function(elem) { 
    if(!scope.searchText) return true;
    return elem.last_name.toLowerCase().indexOf( scope.searchText.toLowerCase()) == 0; 
};

}

}

http://jsbin.com/OyubElO/1/edit- Here is where I'm at right now.

http://jsbin.com/OyubElO/1/edit- 这就是我现在所处的位置。

  <ul border="1px" ng-repeat="msg in messages | filter:search:strict">

<li>{{msg.last_name}}</li>

Any help would be greatly appreciated!

任何帮助将不胜感激!

回答by mark

A simple way to do this is to add a new method to your scope.

一个简单的方法是向您的范围添加一个新方法。

$scope.startsWith = function (actual, expected) {
    var lowerStr = (actual + "").toLowerCase();
    return lowerStr.indexOf(expected.toLowerCase()) === 0;
}

Then change the filter syntax on your element.

然后更改元素上的过滤器语法。

<ul border="1px" ng-repeat="msg in messages | filter:search:startsWith">

Here is a working plunkrwith the example above.

这是一个带有上述示例的工作 plunkr

回答by user3454062

Filter in object

过滤对象

  $scope.fmyData = $filter('filter')($scope.AllMyData, $scope.filterOptions,function (actual, expected) {
                    return actual.toLowerCase().indexOf(expected.toLowerCase()) == 0;
                });

回答by vissu

Now pure javascriptitself has the startsWith()method on strings. But it will not be supported by IE11.

现在 purejavascript本身就有了startsWith()字符串的方法。但它不会被IE11.

See here:

看这里:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith