gpt4 book ai didi

javascript - 强制自定义过滤器重复工作

转载 作者:行者123 更新时间:2023-12-01 03:54:39 25 4
gpt4 key购买 nike

我需要在循环中使用过滤器。假设我们有一个简单数组,其名称为:['Thomas', 'Brian', 'Joana']。我想查看过滤后的名称集。当我使用 Angular 的过滤器时,它按预期工作:

<input ng-model="filterText" />
<span ng-repeat="name in names | filter:filterText">{{name}}</span>

但是当我想使用一些自定义过滤器方法时,当“filterText”输入的值更改时它不起作用:

<input ng-model="filterText" />
<span ng-repeat="name in names | filter:filterMethod">{{name}}</span>

在js文件中:

$scope.filterMethod = function(item) {
if ($scope.textFilter==item || $scope.textFilter==null) {
return true;
}
return false;
}

当用户更改“filterText”输入时,我想始终对名称列表强制执行过滤操作,但实际上仅当该列表由 Angular 预定义过滤器过滤时才会更改。完整的 plnkr 示例:plnkr

最佳答案

像这样实现自定义过滤器

$scope.filterMethod = function(name) {
return function(item){
if(!name ) return item;

if (name && item.startsWith(name)) {
return item;
}
}
}

并像这样在html中调用过滤器

<span ng-repeat="name in result = (names | filter:filterMethod(filterText))">

angular.module("app",[])
.controller("ctrl",function($scope){

$scope.names = ['Thomas', 'Brian', 'Joana'];

$scope.filterMethod = function(name) {
return function(item){
if(!name ) return item;

if (name && item.startsWith(name)) {
return item;
}
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<input ng-model="filterText" />
<span ng-repeat="name in result = (names | filter:filterMethod(filterText))">
{{name}}
</span>
</div>

关于javascript - 强制自定义过滤器重复工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42873004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com