0

i'm having a problem with my angular code.

I'm trying to filter and array using angular filter service but when i get to filtering the array in the filter it duplicates instead of taking each element in the array, i have tried track by but it does not seem to be working.

Here is my angular code:

.filter('priceRange', function() {
        return function(arr, range) {
            if (!range) {return arr; }
            var priceResult = [];
            var pRange = range.split('-');
            angular.forEach(arr, function(key, index) {
                if (key.pPice >= pRange[0] && key.Price <= pRange[1]) {
                    priceResult.push(key);
                }
            })
            console.log(arr);
            return priceResult;
        }
    })

Here is my html sep up:

<div class="col s12 m3" ng-repeat="car in [1,2,3,4,5] | priceRange" >
</div>

when i console.log the array in the filter section i get :

 [1, 2, 3, 4, 5]    rentTatu.js (line 66)
 [1, 2, 3, 4, 5]    rentTatu.js (line 66)
 [1, 2, 3, 4, 5]    rentTatu.js (line 66)
 [1, 2, 3, 4, 5]    rentTatu.js (line 66)
 [1, 2, 3, 4, 5]    rentTatu.js (line 66)

when i try that with a different array i still get duplicates of the array five tims

2
  • Please check this line- key.pPice >= pRange[0] && key.Price <= pRange[1] , it has wrong variable name key.Price, it should be key.pPrice. Commented Mar 7, 2016 at 11:20
  • @ Shailendra Singh Deol thanks that is the answer was just a stupid spelling mistake... Commented Mar 7, 2016 at 13:13

2 Answers 2

1

The filter takes a parameter range which is not set when the filter is called. The html should be like,

<div class="col s12 m3" ng-repeat="car in [1,2,3,4,5] | priceRange: range" >

where range is the input to the parameter in the filter. The line after the if loop will not be executed unless you pass the parameter.

Sign up to request clarification or add additional context in comments.

Comments

1

Hello it seems to me that range value is empty or null, so the whole array is returned , each time it goes to execute the filter , that's why you get the array five times.

What is the value of 'range' variable?

3 Comments

hi,thanks for the reply,the range value is a select tag that has a range of prices in each option. But i dont think that is the problem because i console.loged the array and the filter duplicated the array five time instead of filtering it
Have you tried console.log('range'); into your filter? After that line : if (!range) {return arr; }
Yes,it returns the option value selected ,such as 0-4000

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.