javascript Angularjs:大于使用 ng-repeat 的过滤器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17972775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:17:07  来源:igfitidea点击:

Angularjs: greater than filter with ng-repeat

javascriptangularjsangularjs-ng-repeatng-repeat

提问by Julien

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

我正在对 ng-repeat 标签应用大于过滤器。我编写了以下自定义过滤器函数:

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

and I use it in the following HTML code:

我在以下 HTML 代码中使用它:

<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?

更新 $scope.minPrice 时触发刷新 ng-repeat 标签的最佳方法是什么?

回答by zs2020

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

它应该是自动的。当$scope.minPrice改变时,中继器将自动更新。

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

Demo on jsFiddle

回答by Oliver

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

使用 angularjs 过滤器 api 将过滤器创建为过滤器服务,并添加 minPrice 作为参数。

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/

请参阅此小提琴中的示例:http: //jsfiddle.net/Zmetser/BNNSp/1/