【问题标题】:Angularjs: greater than filter with ng-repeatAngularjs:大于使用 ng-repeat 的过滤器
【发布时间】:2013-07-31 14:10:50
【问题描述】:

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

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

我在下面的 HTML 代码中使用它:

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

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

【问题讨论】:

  • 它确实如 Sza 所述自动刷新,我在表单中绑定 minPrice 时出错。我很抱歉。

标签: javascript angularjs angularjs-ng-repeat ng-repeat


【解决方案1】:

它应该是自动的。当$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

【讨论】:

    【解决方案2】:

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

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

    在模板中

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

    在这个小提琴中看一个例子:http://jsfiddle.net/Zmetser/BNNSp/1/

    【讨论】:

    • 我只会创建一个注册的过滤器,只有当它实际上是可重用的,或者我在多个范围内过滤相同类型的实体时,不能共享过滤器功能
    • 您可以将针传递给您要比较的对象属性,并且您有一个用于对象数组的可重用 GT 过滤器。这样你的控制器会更轻。但你也是对的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-26
    • 1970-01-01
    相关资源
    最近更新 更多