Chcę odfiltrować wszystkie obiekty z ilościąmniej niż 1 i musiałem stworzyć niestandardowy filtr, aby to osiągnąć. Miałem nadzieję, że istnieje prostsze rozwiązanie problemu niż niestandardowy filtr.
Następujące będzie nie praca:
<tr ng-repeat="product in products | filter: {quantity: "!0"}">
Spowoduje to odfiltrowanie 10,20 i tak dalej, oprócz 0.
Skończyło się używanie tego niestandardowego filtru:
app.filter("quantityFilter", function() {
return function( products) {
var filtered = [];
angular.forEach(products, function(product) {
if(product.quantity > 0 ){
filtered.push(product);
}
});
return filtered;
};
});
HTML:
<tr ng-repeat="product in products | quantityFilter">
Czy istnieje płynniejsze rozwiązanie tego problemu? Lubić (nie działa):
<tr ng-repeat="product in products | filter: {quantity: >0}">
Odpowiedzi:
2 dla odpowiedzi № 1Zamiast pisać osobny filtr, możesz użyć funkcji predykatu dla filtra. Zostało to opisane szczegółowo w AngularJS dokumentacja.
więc dla ciebie staje się to:
<tr ng-repeat="product in products | filter:noZeroQuantity">
i w kontrolerze:
$scope.noZeroQuantity = function(value, index, array) {
return value.quantity !== 0;
}
Napisałem przykład w jsfiddle.