kitsune kitsune - 3 months ago 12
Javascript Question

Filter only one or more elements while using ng-repeat

I would to print only some and not all elements of an array that will be printed using ng-repeat.

The array is stored in

$scope.userRecipes = []
.

In the HTML I use:

<li ng-repeat="f in userRecipes" class="list-group-item">

...

<div class="row panel-body" ng-show="!f.isCollapsed">
<hr>
<div class="col-md-6">
<h3>{{f.trigger.triggerType | capitalize}} trigger</h3>
<div ng-repeat="(key, data) in f.trigger" ng-if="!(key == 'triggerType')
|| !(key == 'lastCheck')
|| !(key == 'sender')
|| !(key == 'gaid')
|| !(key == 'ctid')
">
<h4>{{key | reformat | capitalize}}:</h4> {{data}}
</div>
</div>

<div class="col-md-6">
<h3>{{f.action.actionType | capitalize}} action</h3>
<div ng-repeat="(key, data) in f.action" ng-if="key.toString().localeCompare('actionType') || data.notNull() || !data">
<h4>{{key | reformat | capitalize}}:</h4> {{data}}
</div>
</div>
</div>
...

</li>


But this solution (
ng-if="!(key == 'triggerType') || !(key == 'lastCheck') || ..."
) is not working for me. It works only if I set a single condition:
ng-if="!(key == 'triggerType')"
works if leaved alone. If I use
ng-if="!(key == 'triggerType') || !(key == 'lastCheck')
it does not work.

Note that
reformat
and
capitalize
are two AngularJS
myApp.filters(...)
.

Summary: the goal is to make sure that the
ng-repeat
ignores those elements that have some specifics key or data (without printing empty HTML lines).

Answer

The logic in your ng-if is flawed. You're returning true if any of the conditions are true, so you're getting true on every iteration. You want the logical and operator, not or.

<div ng-repeat="(key, data) in f.trigger" ng-if="!(key == 'triggerType')
         && !(key == 'lastCheck')
         && !(key == 'sender')
         && !(key == 'gaid')
         && !(key == 'ctid')
         ">

Now you're returning true if all of them are true, which is what you really want.

Comments