Angularjs自定义过滤器无法正常工作

时间:2017-03-23 21:33:42

标签: html angularjs angularjs-filter angularjs-slider

我正在尝试根据范围过滤元素。我正在使用两个控制器和$rootScope广播接收方法,用于检索滑块的最小 - 最大范围&与其他控制器共享。

HTML -

<body ng-app="myApp">
<div ng-controller="RangeController as vm">
    <rzslider rz-slider-model="vm.slider.minValue" rz-slider-high="vm.slider.maxValue" rz-slider-options="vm.slider.options"></rzslider>
</div>
<div ng-controller="SampleController">
    <div ng-repeat="x in elements | inRange:min:max">
        {{x}}
    </div>
</div>
</body>

AngularJS -

var app = angular.module('myApp', ['rzModule']);
app.controller('SampleController', function($scope,$rootScope) {
    $scope.min = 1500;
    $scope.max = 5500;
    $scope.elements = [1530,2100,2780,3323,3420,4680,5020,5300,5402];

    $scope.$on('MIN_PRICE', function(response) {
        $scope.min = minPrice;
    })

    $scope.$on('MAX_PRICE', function(response) {
        $scope.max = maxPrice;
    })
});

app.value('minPrice',1500);
app.value('maxPrice',5500);

app.controller('RangeController', RangeController);
function RangeController($scope,$rootScope) {
    var vm = this;
    vm.changeListener = function() {
        minPrice = vm.slider.minValue;
        maxPrice = vm.slider.maxValue;
        console.log(minPrice + " " +maxPrice);
        $rootScope.$broadcast('MIN_PRICE', minPrice);
        $rootScope.$broadcast('MAX_PRICE', maxPrice);
    };

    vm.slider = {
        minValue: 1500,
        maxValue: 5500,
        options: {
            floor: 1500,
            ceil: 5500,
            step: 500,
            translate: function(value) {
                return '₹' + value;
            },
            onChange:vm.changeListener
        }
    }   
}   

app.filter('inRange', function() {
    return function(array, min, max) {
        array = array.filter(function(element) {
            return (element >= min && element <= max);
        });
        console.log(array);
    };
});

我尝试过调试,过滤器运行正常,但它不会反映在模板中。

1 个答案:

答案 0 :(得分:2)

我对过滤器中array的自我分配(array = array.filter(…);)似乎对我有点怀疑。您是否尝试过直接返回array.filter(…);

app.filter('inRange', function() {
    return function(array, min, max) {
        return array.filter(function(element) {
            return (element >= min && element <= max);
        });
    };
});