0

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.

4
  • What is value ? Can you share it here ? Commented Jan 13, 2017 at 14:42
  • value is a attribute of $scope that get by promise. Commented Jan 13, 2017 at 14:45
  • 2
    It probably isn't initialized yet when the filter first kicks of, as you say that value is resolved by a promise. This means that value first is undefined, and you cannot run .split on undefined. Just do a check in your filter: if(!x) return x Commented Jan 13, 2017 at 14:46
  • It is indeed that. I add if(!x), Thank Commented Jan 13, 2017 at 14:50

1 Answer 1

2

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

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

3 Comments

if(x) only checks, if the value is truthy. if x is e.g. 1, it will crash.
Right. But I'm sure value is a string. Anyway I used ngClock to wait for values to have value.
You can never be sure :) Words of experience !

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.