Angularjs: greater than filter with ng-repeat

2019-02-13 19:57发布

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?

2条回答
做自己的国王
2楼-- · 2019-02-13 20:02

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

查看更多
冷血范
3楼-- · 2019-02-13 20:07

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/

查看更多
登录 后发表回答