-->

Angularjs: greater than filter with ng-repeat

2019-02-13 19:38发布

问题:

I'm applying a greater than filter to a ng-repeat tag. I wrote the following custom filter function:

$scope.priceRangeFilter = function (location) {
    return location.price >= $scope.minPrice;
};

and I use it in the following HTML code:

<div ng-repeat="m in map.markers | filter:priceRangeFilter">

What is the best way to trigger a refresh of the ng-repeat tag when $scope.minPrice is updated?

回答1:

It should be automatic. When $scope.minPrice is changed, the repeater will be automatically updated.

function Ctrl($scope,  $timeout) {
    $scope.map = [{
        name: 'map1',
        price: 1
    }, {
        name: 'map2',
        price: 2
    }, {
        name: 'map3',
        price: 3
    }];
    $scope.minPrice = 0;
    $scope.priceRangeFilter = function (location) {
        return location.price >= $scope.minPrice;
    };

    $timeout(function () {
        $scope.minPrice = 1.5;
    }, 2000);
}

Demo on jsFiddle



回答2:

Create the filter as a filter service using the angularjs filter api, and add minPrice as a parameter.

filter('priceRangeFilter', function ( location ) {
    return function ( location, minPrice ) {
        ...
    }
})

and in the template

<div ng-repeat="m in map.markers | priceRangeFilter:minPrice">

See an example in this fiddle: http://jsfiddle.net/Zmetser/BNNSp/1/