Search code examples
javascriptangularjsangularjs-filter

Undefined param of filter in AngularJS


I have a filter in AngularJS but when I try to represent value in the view with this filter, I get undefined x.

My code:

.filter('param', function() {
    return function(x) {
        console.log(x);
        return x.split('__')[0];
    };
})

view

{{value | param}}

Result

angular.js:13920 TypeError: Cannot read property 'split' of undefined

I suspect it is that when loading the page I still do not have the value because it is obtained from a promise.


Solution

  • This should help:

    .filter('param', function() {
        return function(x) {
            if(x && typeof x === "string") return x.split('__')[0];
            else return x;
        };
    })
    

    Explanation :

    You can apply the split function only of x has some value, in other terms, when x is not null or undefined.

    Hence, we add a check to validate the variable x