0

I'm learning Angular. The below code dynamically shows/hides rows of a table based on a <select multiple> control.

The code works but I wonder if there is a way to convert the expression in data-ng-if to a filter expression without creating a custom filter. Also not sure which is a better approach performancewise.

<select id="psgs" data-ng-model="ctrl.showSubGroups"
   ng-options="item.id as item.name group by item.productGroup.name for item in ctrl.productSubGroupList"
   multiple>
</select>

<tr 
   data-ng-if="ctrl.showSubGroups.indexOf(product.productSubGroup.id) > -1" 
   data-ng-repeat="product in ctrl.productList | filter: ??? | orderBy: ctrl.seq">
   ...
</tr>
6
  • what kind of filtration you want?, any use case Commented Apr 2, 2017 at 9:31
  • Exactly the same as in ng-if, but as a filter expression. Commented Apr 2, 2017 at 9:35
  • again, there can be many scenarios.. like ng-if="$even", can filter out odd result.It all depends on your use case. If you have a particular requirement, state it in question. Commented Apr 2, 2017 at 9:50
  • @Arthur why do you not want to use a custom filter? Commented Apr 2, 2017 at 9:55
  • @tanmay Because I'm also not sure how to access the array of selected subgroups stored as a controller property from a filter. Commented Apr 2, 2017 at 10:01

1 Answer 1

1

You can achieve that using custom filter and it's better approach as compared to having ng-if on each iteration. You shouldn't be repeating the loop for those which are not going to be rendered.

Here's how. In your HTML, use customFilter (which is a custom filter function we created) like this:

<tr 
   data-ng-repeat="product in ctrl.productList | filter: ctrl.customFilter | orderBy: ctrl.seq">
   ...
</tr>

Now, in your controller, you can have customFilter function like this:

ctrl.customFilter = function(product) {
  return ctrl.showSubGroups.indexOf(product.productSubGroup.id) > -1
}

Here's a simple working example with sample data

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, it is easier than what I thought from the documentation. :)
@Arthur in Angular most of the things are easier than shown in docs :D glad I could help

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.