F
F
Friend2016-10-19 05:33:04
Django
Friend, 2016-10-19 05:33:04

How to get around filter issue when loading json file in AngularJS?

Using AngularJS, I upload json to an html page through filters, earlier json text was written in the js file, but when the file is connected, angular.min.js:118 TypeError: Cannot read property 'length' of undefined swears . The problem crashes only if I use filters that I have registered on several variables:

iApp.filter('filterprice', function () {
        return function (allobj, price1, price2) {
        var filteredMaterials = [];
        if (price1 === undefined){
            price1 = 0;
        }if (price2 === undefined){
            price2 = 999999;
        }

        if (price1 === ''){
            price1 = 0;
        }if (price2 === ''){
            price2 = 999999;
        }

        for (var i = 0; i < allobj.length; i++) {
            if (allobj[i]){

            }
            if (allobj[i]['price'] >= price1 && allobj[i]['price'] <= price2) {
                filteredMaterials.push(allobj[i]);
            }
        }
        return filteredMaterials;
        };
});

Using 1 such filter, it simply throws an error and displays everything, using 2 displays nothing.
What could be the problem and how to fix it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Manakov, 2016-10-19
@gogolor

So in the console they showed an error. Cannot read property 'length' of undefined. Length is taken from you only from allobj, which means at some point it is undefined. You're loading the json asynchronously, so the filter runs on an undefined object. Quick crutch:

return function (allobj, price1, price2) {
  if(allobj == null) return;
  var filteredMaterials = [];

Or put in html on el-t:
ng-if="allobj"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question