我有一些数据是从我的控制器中的API中用$ http.get引入的,然后我想对该文本应用文本格式过滤器以使其完美。
但是我得到了
TypeError: Cannot read property 'split' of undefined
遍布我的控制台。
以下是代码:
Controller $ http get:
$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>
答案 0 :(得分:3)
由于$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;
});
答案 1 :(得分:0)
您不能将滤镜功能用作角度滤镜。另一种解决方案是将过滤器功能放在控制器中,然后从视图中调用它,如下所示:
<div ng-repeat="services in serviceStatus">
<p>The {{ services.service | filter:textFormat }} is {{ services.status | filter:textFormat }}</p>
</div>
确保textFormat
是您的功能名称