0

I have a following Multidimensional Array in the controller.

var app = angular.module('myApp',[]);
app.controller('myController',function($scope){
   $scope.myData = [{name:'Person1',surname:'Surname1'},
                    {name:'Person2',surname:'Surname1'},
                    {name:'Person3',surname:'Surname2'},
                    {name:'Person4',surname:'Surname3'},
                    {name:'Person5',surname:'Surname3'}];
});

I've tried following code to use limitTo and filter with ng-repeat to filter and limit the display of elements.

<div ng-if="myData.length !== 0"><input type="text" placeholder="Enter name to search" ng-model="mySearch"/></div>
<table>
<thead>
  <tr>
   <th>Name</th>
   <th>Surname</th>
  <tr>
</thead>
<tbody>
  <tr ng-repeat="tr in myData | filter:{name:mySearch} | limitTo: 1:2">
   <td ng-bind="tr.name" ng-cloak></td>
   <td ng-bind="tr.surname" ng-cloak></td>
  <tr>
</tbody>
</table>

But from the above piece of code I'm only able to limit the records but not able to filter based on the input.

BBRK
  • 102
  • 1
  • 1
  • 12

2 Answers2

0

It is because of the second value you have added to your LimitTo filter. As it is written in the documentation

{{ limitTo_expression | limitTo : limit : begin}}

second value sets the index at which to begin limitation. If you remove 2 from your limitTo your code should work the way you want.

  <tr ng-repeat="tr in myData | filter:{name:mySearch} | limitTo: 1">
   <td ng-bind="tr.name" ng-cloak></td>
   <td ng-bind="tr.surname" ng-cloak></td>
  <tr>

Demo

NTP
  • 4,338
  • 3
  • 16
  • 24
0

The ng-if was causing the issue. I replaced ng-if with ng-show and it worked.

I found the explanation regarding the difference between the two in the following post.

What is the difference between ng-if and ng-show/ng-hide

Code after changes:-

<div ng-show="myData.length !== 0"><input type="text" placeholder="Enter name to search" ng-model="mySearch"/></div>
<table>
<thead>
  <tr>
   <th>Name</th>
   <th>Surname</th>
  <tr>
</thead>
<tbody>
  <tr ng-repeat="tr in myData | filter:{name:mySearch} | limitTo: 1:2">
   <td ng-bind="tr.name" ng-cloak></td>
   <td ng-bind="tr.surname" ng-cloak></td>
  <tr>
</tbody>
</table>

Hope this helps someone.

BBRK
  • 102
  • 1
  • 1
  • 12