sashok1337 sashok1337 - 2 months ago 8
Javascript Question

Applying a angularjs filter after "Apply" button click

I have a big list of data (4000+ items). When start typing - my browser freezes (up to 15 sec). So i need to turn off auto-filter feature, and bind filter function to the button click.
Looking for answer via Google gave no results. How i can do this? Help me please :)

Code:

<input ng-model="search.phone" type="text" placeholder="Телефон...">
<input ng-model="search.name" type="text" placeholder="Имя...">
<input ng-model="search.city" type="text" placeholder="Город...">

<div ng-repeat="user in users | filter:search" class="user_block" ng-include src="userTemplate"></div>


and controller:

app.controller("smsCtrl", ['$scope', 'smsData', 'createDialog', '$http', '$filter', function($scope, smsData, createDialog, $http, $filter){...}

Answer

I found the solution!

Change:

<div ng-repeat="user in users | filter:search" class="user_block" ng-include src="userTemplate"></div>

To:

<div ng-repeat="user in users" ng-hide="user.excludedByFilter" class="sms_user_block" ng-include src="userTemplate"></div>

Add "applySearchFilter" function to controller

    $scope.applySearchFilter = function() {
        var nameFilter = $scope.filters.name.toLowerCase();
        var phoneFilter = $scope.filters.phone;
        var cityFilter = $scope.filters.city;
        var showAll = 0 === nameFilter.length && 0 === phoneFilter.length && 0 === cityFilter.length;
        angular.forEach($scope.users, function(user) {
            if (showAll) {
                user.excludedByFilter = false;
            } else {
                user.excludedByFilter = (user.name.toLowerCase().indexOf(nameFilter) === -1) 
                                        || (user.phone.indexOf(phoneFilter) === -1) 
                                        || (user.city.indexOf(cityFilter) === -1);
            }
        });
    }

And add html code for filter button:

<a class="btn btn-primary" href="#" ng-click="applySearchFilter()">Apply filters</a>

And this works!

*Note, that I renamed ng-model="search.*" to ng-model="filters.*" in inputs.