Home > Mobile >  How to define a custom filter in AngularJS
How to define a custom filter in AngularJS

Time:01-31

I'm fairly new to AngularJS and still trying to grasp the basics. I'm trying to define a custom filter for my select dropdown. I have the logic but I don't know where to exactly implement it, and what I should modify on my html.

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>

I want to replace filter by a custom filter

js logic

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;   
            }; 
        });

how do I implement this js logic into my controller?

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

CodePudding user response:

Can you be more elaborate on your query. What is the format of the data that you are filtering? And are you using some custom directives (ui-select-match, ui-select-choices) on your html??

If you have an array of regions data like below and if you want to filter that data based on some user input, then u can use the predefined "filter" Filter and pass the "SearchText" to that filter in the html file.

<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"}
    ];
  • Related