Replace ng-if
in ng-repeat
with Custom Filter:
Create a custom filter:
app.filter("myFilter", function() {
return function (list) {
return list.filter(function(item) {
return item.default_quantity == 0 &&
item.entry.quantity > 0;
});
};
})
Use that filter instead of using the ng-if directive:
<p ng-repeat="ingredient in product.options | myFilter">
{{ingredient.entry.full_name}} {{$last}}
<span ng-hide="$last">,</span>
</p> .
This technique is more efficient because it avoids adding watchers and child scopes for each ng-if
. Also $last
and the other special properties of the ng-repeat directive will work as expected.
angular.module("app",[])
.filter("myFilter", function() {
return function (list) {
return list.filter(function(item) {
return item.default_quantity == 0 &&
item.entry.quantity > 0;
});
};
})
.controller("ctrl", function($scope) {
var vm=$scope;
vm.product = { options: [
{ default_quantity: 0,
entry: { quantity: 4, full_name: "fullname0"}
},
{ default_quantity: 0,
entry: { quantity: 4, full_name: "fullname1"}
},
{ default_quantity: 1,
entry: { quantity: 4, full_name: "fullname2"}
},
]
};
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app" ng-controller="ctrl">
GOOD
<p ng-repeat="ingredient in product.options | myFilter">
{{ingredient.entry.full_name}} {{$last}}
<span ng-hide="$last">,</span>
</p> .
<hr>BAD
<p ng-repeat="ingredient in product.options"
ng-if="ingredient.default_quantity == 0 &&
ingredient.entry.quantity > 0">
{{ingredient.entry.full_name}} {{$last}}
<span ng-hide="$last">,</span>
</p> .
</body>