Samantha J Samantha J - 4 months ago 11
AngularJS Question

How can I dynamically limit data showing in an ng-repeat?

I have this ng-repeat that I show split over three rows here for clarity:

ng-repeat="row in phs.phrasesView =
(phs.phrases | orderBy:phs.phrasesOrderBy[phs.phrasesOrderById]
.key:phs.phrasesSortDirectionId == 1)">


On my form I have a field
phs.keywordRange


Is there a way that I can make it so the rows returned are filtered as follows:


  • When phs.keywordRange is null or empty string, all rows are shown

  • When phs.keywordRange is
    A
    then only rows where row.keyword starts with
    A
    are shown

  • When phs.keywordRange is
    ABC
    then only rows where row.keyword starts with
    ABC
    are shown


Answer

Make your own filter, like this fiddle. Changing the $scope.keywordRange will update the list accordingly.

as shortcut:

.filter('keywordRange', function() {
   return function(value, keyword) {

   var out = [];

   if(!keyword) {
     return value;
   }

   for(var i = 0; i < value.length; i++) {
     if(value[i].startsWith(keyword)){
       out.push(value[i]);
     }
   }

   return out;
  };
});

function MyCtrl($scope) {
  $scope.keywordRange = 'ti';

  $scope.lines = [
    'rest1', 'rest2', 'tiago', 'pedro', 'america'
  ];
}

and the html

<div ng-controller="MyCtrl">
   <div ng-repeat="line in lines | keywordRange:keywordRange">

     <p>{{line}}</p>
   </div>
</div>
Comments