Search code examples
angularjssearchangularjs-filter

Using angularjs custom filter instead of a function to perform a search


I am currently using a filter function (not a custom filter) on ng-repeat. However I have been told that using a custom filter is better performance. How would I go about using a custom filter to do the same search as this:

        $scope.searchInOrder = function (item)
        {
            if($scope.search)
            {
                if(item.match("^"+$scope.search, "i"))
                {
                    return item;
                }
            }
            else
            {
                return item;
            }
        }

Here is my fiddle.

So I use this filter using "key in keyboard.keys | filter: searchInOrder" but how do I do the same thing using a custom filter e.g. "key in keyboard.keys | customSearchInOrder:search" is it better for performance doing it this way (with a custom filter instead of a function) and if so why? Also which way is better for code maintainability?


Solution

  • Which way is better? This totally depends on your requirements and application. Because repeated filter may lead to performance issues. As explained in this very good post Angular Performance tips . So its for you to decide wha will be the best fir for your case a custom filter or filtering in code.

    But if you are not worried about this then yes a custom filter would be good. As it will be reusable and you need not to repeat the filtering again in case you need the same filter for different views/controllers. Below is a custom filter for your case.

    Updated Fiddle

    var app = angular.module('myApp', []);
    
    app.controller('myCtrl', function($scope) {
    
    
    
      $scope.keyboard = {
        "keys": ["cntrlA", "cntrlB", "cntrlC", "cntrlD", "space1", "space2", "space3", "shift"]
      }
    
    });
    
    app.filter('searchKeys', function() {
      return function(items, search) {
        var filtered = [];
        if (search) {
          angular.forEach(items, function(item) {
            if (item.match("^" + search, "i")) {
              filtered.push(item);
            }
          });
        }else{
        	filtered=items;
        }
        return filtered;
      }
    })
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
    <div data-ng-app='myApp' data-ng-controller='myCtrl'>
    
      <!-- using scope function as a filter -->
      <input ng-model="search" placeholder="Search..." />
      <div ng-repeat="key in keyboard.keys | searchKeys: search">
        {{key}}
      </div>
    </div>

    Hope it helps :).