David Sonnenfeld David Sonnenfeld - 2 months ago 10
AngularJS Question

Bind data from pagination to filter in Angular

I have a simple pagination with letters:

<div ng-controller="DataController">
<ul class="pagination">
<li ng-repeat="letter in data_letters">
<a href="#" ng-click="setLetter(letter)">{{letter}}</a>
</li>
</ul>
<table class="table table-striped">
<tbody>
<tr>
<th>Name</th>
<th>State</th>
</tr>
<tr ng-repeat="person in persons | startsWithLetter:letter">
<td>{{person.Name}}</td>
<td>{{person.State}}</td>
</tr>
</tbody>
</table>
</div>


What is the easiest way to bind the letter (on which we clicked at the paginaton) to the table filter.
Here is a fully functional plunkr: http://plnkr.co/edit/Trr5LzrcMfZqonD0jvjX?p=preview

I have everything implemented already. It is just the data-binding which is missing. Any ideas?

Answer

One issue with your code is that you are unnecessarily injecting $scope into your filter:

app.filter('startsWithLetter', function($scope) {

should be

app.filter('startsWithLetter', function() {

The other issue is using 'C-D' as a filter value. I would change $scope.data_letters to be an array of objects that contain a key/value pair like this:

$scope.data_letters = [{
  key: 'A',
  value: "A"
}, {
  key: "B",
  value: "B"
}, {
  key: ['C', 'D'],
  value: "C-D"
}];

Then change your check in the filter to evaluate all keys, like this:

  angular.forEach(letters, function(letter, key) {
    if (itemName.startsWith(letter)) {
      filtered.push(items[i]);
    }
  });

You can see it working here where I forked your plunk.

Comments