Search code examples
htmlangularjsangularjs-filterangularjs-slider

Angularjs custom filter not working


I am trying to filter elements based on the range. I am using two controllers & $rootScope broadcast-on approach to retrieve the min-max range of a slider & sharing it with the other controller.

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);
    };
});

I tried debugging, the filter works fine but it won't reflect in the template.


Solution

  • The self-assignment to array inside your filter (array = array.filter(…);) seems slightly suspicious to me. Have you tried simply returning array.filter(…); directly?

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