gpt4 book ai didi

angularjs - angularjs 中的 Ucwords 过滤器抛出错误

转载 作者:行者123 更新时间:2023-12-04 19:57:20 26 4
gpt4 key购买 nike

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

HTML 片段:

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

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

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

如果输入是 show me first title那么输出将是 Show Me First Title . 但是为什么它首先抛出错误 ?我正在考虑使用 $timeout在过滤器中,但这不是一个好方法。任何人都可以建议我最好的方法吗?

下面是错误 :
Error: input is undefined

最佳答案

filters are evaluated on each digest cycle



初始值 defaultProduct.Campaign.title未定义决定 async称呼。那时您的自定义过滤器会在设置 defaultProduct.Campaign.title 之前被调用值(value)。过滤器尝试 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;
}
})

关于angularjs - angularjs 中的 Ucwords 过滤器抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31703416/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com