Angularjs: greater than filter with ng-repeat

拈花ヽ惹草 提交于 2019-11-30 05:41:08

问题


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/



来源:https://stackoverflow.com/questions/17972775/angularjs-greater-than-filter-with-ng-repeat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!