Search code examples
javascriptangularjsangularjs-ng-repeatangularjs-filter

How to ng-repeat only after applying the filter?


First of all, let me mention that I am new to AngularJS, and programming aswell. My situation is as follows:

I am dealing with over 50k entries that I pull from a SQL database.

I have to show those entries on a web platform after a search/filter is applied on those entries.

So I did some research on this and came to the conclussion that the way to go is: SQL>PHP>JSON>ANGULARJS. I got all this down , the thing is that ng-repeat sends everything to the browser and what I want is to filter the results and THEN print them with ng-repeat.

I have tried to implement a filter of sorts but I can't seem to solve it.

Code looks like this:

js:

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

app.controller('MainCtrl', function($scope, $http)
{
  $http.get("http:source.php")
  .then(function(response)
  {
    $scope.materiale = response.data.records;
  });
});

app.filter('filtruCautare', function () {
    return function (items, filtru) {
        var filtered = [];
        var filtruMatch = new RegExp(filtru, 'i');
        for (var i = 0; i < items.length; i++) {
            var item = items[i];
            if (filtruMatch.test(item.MATKL) || filtruMatch.test(item.MAKTX)) {
                filtered.push(item);
            } else if (filtruMatch.test(item.MATNR)) {
                    filtered.push(item);
            }
        }
        return filtered;
    };
});

html:

 <input ng-model='filtru' type="text" placeholder="...">

<tbody ng-repeat="material in materiale | filtruCautare:filtru">

I've put this together from several blogs, Stackoverflow posts/questions and other several sources...

I think that I need to somehow filter the 50k entries, store them inside a scope and use the ng-repeat to print the results from there, it's just that I'm having trouble creating a scope that pulls info from the filter.

Any help is appreciated!


Solution

  • Simply change your filter in order to return an empty array if the search filter is not defined (or is an empty string).

    In this way you will start to see results only when you start filtering:

    app.filter('filtruCautare', function () {
        return function (items, filtru) {
            if (!filtru) { 
              return [];
            }
            var filtered = [];
            var filtruMatch = new RegExp(filtru, 'i');
            for (var i = 0; i < items.length; i++) {
                var item = items[i];
                if (filtruMatch.test(item.MATKL) || filtruMatch.test(item.MAKTX)) {
                    filtered.push(item);
                } else if (filtruMatch.test(item.MATNR)) {
                        filtered.push(item);
                }
            }
            return filtered;
        };
    });