Angular filter with minimum and maximum values
Solution 1
Unfortunately, I can't pinpoint exactly the problem you're having with your code. However, I think I have created a plnkr that (I believe) works as intended.
Apart from parsing the inputs with parseFloat, the logic seems to be the same. Not parsing the inputs to a numeric form shouldn't "break" it, but will possibly make it behave strangely ("9" > "10" for example).
Anyway, hopefully you can pull out the useful pieces and get it working.
Solution 2
To ensure the model values are numbers and not strings, change the type
for your inputs to be number
.
<input type="number" ng-model="minHorsepower" />
<input type="number" ng-model="maxHorsepower" />
Also, make sure your model values are numbers and not strings.
Alternatively, you can run everything through parseFloat(...)
in your filter.
Solution 3
Since you only send to the filter a function, it doesn't know to watch for any value changes, and thus to trigger the filter function when it happens.
When you define a filter as {{ filter_expression | filter : filterValue}}, angular watches the filterValue and triggers the filter function when it changes.
To achieve what you need you can define your own filter:
angular.module('myApp')
.filter('range', function(){
return function(items, property, min, max) {
return items.filter(function(item){
return item[property] >= min && item[property] <= max;
});
};
});
and call it like this:
ng-repeat="plane in planes | range : 'horsepower' : minHorsepower : maxHorsepower"
Comments
-
Andrew Samuelsen almost 2 years
I'm having some trouble getting angular to properly filter my results. I'm attempting to use a custom filter that gets arguments from a minimum input and a maximum input.
/index.html
<input ng-model="minHorsepower"> <input ng-model="maxHorsepower"> ... tr(ng-repeat="plane in planes | filter:horsepowerFilter")
/controllers.js
//Horsepower filter $scope.horsepowerFilter = function(plane) { var ret = true; if($scope.minHorsepower && $scope.minHorsepower > plane.horsepower) { ret = false; } if($scope.maxHorsepower && $scope.maxHorsepower < plane.horsepower) { ret = false; } return ret; }; $scope.planes = [ { 'make' : 'Piper', 'model' : 'Arrow', 'modelNumber' : 'PA-28R-180', 'horsepower' : '180', 'gear' : 'retractable', }, { 'make' : 'Piper', 'model' : 'Arrow', 'modelNumber' : 'PA-28R-200', 'horsepower' : '200', 'gear' : 'retractable', } ];
It works INITIALLY when I set $scope.minHorsepower/$scope.maxHorsepower in controllers.js, but only initially, not when I put something else in the
<input>
s. Furthermore, it prefills the inputs AND filters the results. It just doesn't work properly when I change the value of the inputs.I've referenced this Stack Overflow thread, but I can't find any material differences in our code... AngularJS multiple filter with custom filter function
Thanks for the help.