1

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...

4
  • can you detail all the filtering that you want to do, i only see one filtering here. Commented Jun 20, 2016 at 13:04
  • I try do not repeat (person in people|filter:{show:true}) everywhere Commented Jun 20, 2016 at 13:05
  • If you need to show the same filtered version of a list frequently, the most performant way is to construct a filtered version of the myPeople array inside the controller and include that in your template. Commented Jun 20, 2016 at 13:10
  • yes, but if I have different filters in different combinations... creating for each of them a variable could bring some mess in the code, isn't it Commented Jun 20, 2016 at 13:12

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

2 Comments

I used ng-init and ng-if on the same element! ) is that a problem?
Yes, you need to have ngIf inside, because due to very high priority it's executed before ngInit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.