如何在AngularJS中定义自定义过滤器

wnvonmuf  于 2023-01-29  发布在  Angular
关注(0)|答案(1)|浏览(184)

我对AngularJS还是个新手,还在努力掌握基础知识。我正在尝试为我的下拉菜单定义一个自定义过滤器。我有逻辑,但我不知道在哪里实现它,以及我应该在我的html上修改什么。
超文本标记语言

<ui-select multiple ng-model="criteria.regionIds" theme="select2" style="width: 100%;border:0!important;">
         <ui-select-match placeholder="Select regions...">{{$item.label}}</ui-select-match>
         <ui-select-choices repeat="region.code as region in regions | filter:$select.search">
             <div ng-bind-html="region.label | highlight: $select.search"></div>
         </ui-select-choices> 
    </ui-select>

我想用自定义筛选器替换筛选器
js逻辑

app.filter('myCustomeFilter', function() { 
    return function(items, props) { 
        var out = []; 
        if (angular.isArray(items)) { 
            items.forEach(function(item) { 
                var keys = Object.keys(props); 
                var prop = keys[0]; 
                var text = props[prop].toLowerCase(); 
                if (item[prop].toString().toLowerCase().indexOf(text) === 0) { 
                   out.push(item);
                }
              });
        } else { 
             out = items;
        } 
          return out;   
            }; 
        });

我如何在我的控制器中实现这个js逻辑?

function summaryReportsResultsCtrl($scope, $state, $filter, $modal, growl, summaryreportService, paginationConfig, currentUser) { 
// inside the controller 
}
4uqofj5v

4uqofj5v1#

你能更详细地说明你的查询吗?你过滤的数据是什么格式的?你在你的html中使用了一些自定义指令(ui-select-matchui-select-choices)吗?
如果你有一个区域数据数组,如下图所示,如果你想根据用户输入过滤数据,那么你可以使用预定义的“filter”过滤器,并将“SearchText”传递给html文件中的过滤器。

<input type="text" placeholder="Select Regions..." ng-model="searchText"/>
<br/>
<select ng-model="selectedRegions" ng-options="eachRegion.code for eachRegion in regions | filter: searchText" multiple>
</select>


var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {
    $scope.searchText = "Metro";
    $scope.regions = [
        {code: 011, label: "Delhi", type: "Metro"},
        {code: 022, label: "Mumbai", type: "Metro"},
        {code: 033, label: "Kolkatta", type: "Metro"},
        {code: 044, label: "Chennai", type: "Metro"},
        {code: 080, label: "Bangalore", type: "City"},
        {code: 079, label: "Ahmedabad", type: "City"},
        {code: 040, label: "Hyderabad", type: "City"},
        {code: 0612, label: "Patna", type: "City"}
    ];

相关问题