gpt4 book ai didi

javascript - Angular : can't apply a filter to data loaded via $http

转载 作者:行者123 更新时间:2023-11-30 12:09:59 25 4
gpt4 key购买 nike

我使用 $http.get 从我的 Controller 中的 API 提取了一些数据,然后我想对该文本应用文本格式过滤器以使其美观。

但是我得到了

TypeError: Cannot read property 'split' of undefined

在我的控制台上。

代码如下:

Controller $http 获取:

$http.get("url to my api data")
.success(function (data, status, headers, config) {

$scope.serviceStatus = data;

})
.error(function () {

});

模块内过滤:

app.filter('textFormat', function() {
function format(input) {
// Call the passed in endpoint and at any capitalised letters, split it to have a space between words
input = input.split(/(?=[A-Z])/).join(" ");

// Get the character at index 0 and modify it to be uppercase. Then append the rest of the split string to the end
input = input.charAt(0).toUpperCase() + input.slice(1);

return input;
};

format.$stateful = true;

return format;
});

HTML:

<div ng-repeat="services in serviceStatus">
<p>The {{ services.service | textFormat }} is {{ services.status | textFormat }}</p>
</div>

最佳答案

您遇到此问题是因为 $http 是一个 async 调用。它避免了正常的执行流程。您应该将过滤器代码更改为以下一个

app.filter('textFormat', function() {
function format(input) {
if(input) { // Check if the value has been initialized
// Call the passed in endpoint and at any capitalised letters, split it to have a space between words
input = input.split(/(?=[A-Z])/).join(" ");

// Get the character at index 0 and modify it to be uppercase. Then append the rest of the split string to the end
input = input.charAt(0).toUpperCase() + input.slice(1);

return input;
}
};

format.$stateful = true; // You can put these two lines in above code as well.

return format;
});

关于javascript - Angular : can't apply a filter to data loaded via $http,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34087266/

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