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
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;
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With