Search code examples
angularjsangularjs-directiveangularjs-scopeangularjs-ng-repeatangular-filters

AngularJS - Filter not working on data that hasnt been scrolled to


I have a simple ng-repeat that uses a scroll directive. On load, the first 10 results are displayed, on scoll, more results are show.

The issue i am seeing is that when you type a value in the input, the data that is filtered seems to be the data that is displayed at the current time.

So in the example in my plunker: http://plnkr.co/edit/1qR6CucQdsGqYnVvk70A?p=preview

If you type in Last in the textbox after loading the page (do not scroll), that data is never shown. However, if you scroll to the bottom, then type Last, that result is found.

HTML:

<div id="fixed" directive-when-scrolled="loadMore()">
  <ul>
    <li ng-repeat="i in items | limitTo: limit | filter: search">{{ i.Title }}</li>
  </ul>
</div>

<br>


<input ng-model="searchText">
<button ng-click="performSearch(searchText)">Submit</button>

JS:

app.controller('MainCtrl', function($scope, $filter) {  

$scope.name = 'World';
  $scope.limit = 5;


  var counter = 0;
  $scope.loadMore = function() {
    $scope.limit += 5;
  };

  $scope.loadMore();

  $scope.performSearch = function(searchText) {
        $scope.filtered = $filter('filter')($scope.items, $scope.search);
    }

    $scope.search = function (item){
        if (!$scope.searchText)
            return true;

        if (item.Title.indexOf($scope.searchText)!=-1 || item.Title.indexOf($scope.searchText)!=-1) {
                return true;
            }
            return false;
    };


});


app.directive("directiveWhenScrolled", function() {
  return function(scope, elm, attr) {
    var raw = elm[0];

    elm.bind('scroll', function() {
      if (raw.scrollTop + raw.offsetHeight >= raw.scrollHeight) {
        scope.$apply(attr.directiveWhenScrolled);
      }
    });
  };
});

Solution

  • You need to apply the filter before you limit the results:

    <li ng-repeat="i in items | filter: search | limitTo: limit">{{ i.Title }}</li>