David Sonnenfeld David Sonnenfeld - 11 months ago 55
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>
<table class="table table-striped">
<tr ng-repeat="person in persons | startsWithLetter:letter">

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 Source

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)) {

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