Ucwords过滤angularjs投掷错误

Vin*_*eet 5 angularjs

发生了一些奇怪的事情.实际上我正在从异步调用中分配一个标题,我正在ucwords对标题应用过滤器.它给了我正确的输出,但首先抛出错误然后显示正确的值.

HTML片段:

<h1 ng-show="defaultProduct.Campaign.title">{{ defaultProduct.Campaign.title | ucwords }}</h1>
Run Code Online (Sandbox Code Playgroud)

过滤片段

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

请注意defaultProduct.Campaign.title从AJAX调用分配.它在ajax成功之后初始化.在我的控制台中,它首先抛出错误,在ajax成功调用之后它显示正确的输出.

如果输入show me first title则输出Show Me First Title.但为什么它首先抛出错误?我想$timeout在过滤器中使用,但这不是一个很好的方法.谁能建议我最好的方式?

以下是错误:

Error: input is undefined
Run Code Online (Sandbox Code Playgroud)

Pan*_*kar 4

在每个摘要周期评估过滤器

defaultProduct.Campaign.title最初,未定义将决定调用的值async。那时,您的自定义过滤器将在设置defaultProduct.Campaign.title值之前被调用。过滤器尝试input.toLowerCase()返回input is undefined未定义输入值的位置。您通常应该在过滤器本身内部处理这种情况。

筛选

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; 
    }    
})
Run Code Online (Sandbox Code Playgroud)