Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ucwords filter in angularjs throwing error

Tags:

angularjs

Something strange is happening. Actually I am assigning a title from asynchronous call and I'm applying a ucwords filter on the title. It is giving me the proper output but throwing the error first and after then showing the proper value.

HTML snippet:

<h1 ng-show="defaultProduct.Campaign.title">{{ defaultProduct.Campaign.title | ucwords }}</h1>

Filter Snippet

app.filter("ucwords", function () {
    return function (input){
        input = input.toLowerCase().replace(/\b[a-z]/g, function(letter) {
            return letter.toUpperCase();
        });
        return input; 
    }    
})

Please note defaultProduct.Campaign.title is assigning from AJAX call. It initializes after ajax success. In my console it is throwing the error first and after ajax success call it is showing proper output.

If input is show me first title then output will be Show Me First Title. But why it is throwing the error first ? I'm thinking to use $timeout in filter but it would not a good way of doing that. Can anyone suggest me best way ?

Below is the error :

Error: input is undefined
like image 277
Vineet Avatar asked Sep 28 '22 04:09

Vineet


1 Answers

filters are evaluated on each digest cycle

Initially the value of defaultProduct.Campaign.title is not defined that is going to decide async call. At that time your custom filter is gets called before setting defaultProduct.Campaign.title value. Filter tries to input.toLowerCase() which return input is undefined where as input value is not defined. You should typically handle this scenarios inside your filter itself.

Filter

app.filter("ucwords", function () {
    return function (input){
        if(input) { //when input is defined the apply filter
           input = input.toLowerCase().replace(/\b[a-z]/g, function(letter) {
              return letter.toUpperCase();
           });
        }
        return input; 
    }    
})
like image 88
Pankaj Parkar Avatar answered Dec 28 '22 06:12

Pankaj Parkar