Search code examples
javascriptangularjsangular-filters

How to use filters in Angularjs?


I have this collection :

  { id: 1, courseId: 2, text: 'John' },
  { id: 2, courseId: 2, text: 'Willi' },
  { id: 3, courseId: 2, text: 'Inga' },
  { id: 4, courseId: 1, text: 'Jerry' },
  { id: 5, courseId: 1, text: 'Michael' },
  { id: 1, courseId: 3, text: 'John' },
  { id: 2, courseId: 3, text: 'Willi' },
  { id: 3, courseId: 4, text: 'Inga' },
  { id: 4, courseId: 5, text: 'Jerry' },
  { id: 5, courseId: 5, text: 'Michael' }

I want to render in view with help of ng-repeat directive only records that have id =1 and id=2 and id=5.

How can I do it using filter in angularjs?


Solution

  • You need to create a custom filter that will do the trick

    Markup

    ng-repeat="item in items | filterArray: [1, 2, 5]"
    

    Filter

    app.filter('filterArray', function() {
      return function(inputArray, arrayToCompare) {
        return inputArray.filter(function(value) {
          console.log(arrayToCompare.indexOf(value.id), value)
          return arrayToCompare.indexOf(value.id) != -1;
        })
      }
    })
    

    Working PLunkr