Serge Serge - 5 months ago 7
AngularJS Question

Avoid multiple use of a Filter in AngularJs

I am trying to avoid using the same filter on the same collection multiple times in AngularJS application.

What is the correct way to do it:

<div ng-app="myApp" ng-controller="PeopleCtrl">
<ul ng-init="(person in people|filter:{show:true}) as myPeople" ng-if="myPeople.length>0">
<h4>My People</h4>
<li ng-repeat="person in myPeople">{{person.name}}; display: {{person.show}};
</ul>
</div>


CODE PEN

When I use
(person in people|filter:{show:true}) as myPeople
I try to use an alias in order to not repeat the same filter
{show:true}
everywhere...

Answer

You should do it something like this:

<div ng-init="myPeople = (people | filter:{show:true})">
  <div ng-if="myPeople.length>0">
    <h4> My People</h4>
    <ul>
      <li ng-repeat="person in myPeople">
        {{person.name}}; age: {{person.age}}; show: {{person.show}};
      </li>
    </ul>
  </div>
</div>
Comments