Ucwords filter in throwingjs error

Something strange is happening. In fact, I am assigning a header from an asynchronous call, and I am applying the ucwords filter in the header. This gives me the correct conclusion, but first gives an error, and then shows the correct 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[az]/g, function(letter) { return letter.toUpperCase(); }); return input; } }) 

Note: defaultProduct.Campaign.title assigns an AJAX call. It is initialized after ajax success. In my console, it throws an error first, and after ajax call is successful, it shows the correct output.

If the input signal is show me first title , then the output will be show me first title . But why does he first throw a mistake ? I am thinking of using the $timeout filter in the filter, but that is not very good. Can someone suggest me a better way?

The following is the error :

 Error: input is undefined 
+4
source share
1 answer
Filters

evaluated in each digest cycle

Initially, the value of defaultProduct.Campaign.title not defined, which will resolve the async call. At this time, your custom filter is called before setting the defaultProduct.Campaign.title value. The filter tries input.toLowerCase() , which returns input is undefined when the input value is undefined. Usually you should process these scripts inside the filter itself.

Filter

 app.filter("ucwords", function () { return function (input){ if(input) { //when input is defined the apply filter input = input.toLowerCase().replace(/\b[az]/g, function(letter) { return letter.toUpperCase(); }); } return input; } }) 
+3
source

All Articles