我试图在角度上创建一个ES6类控制器。这按预期工作(能够打印通过消息函数返回的字符串)。见下文。
<div ng-controller="ProfilingCtrl as profileData">
{{profileData.message()}}
</div>
但我现在要做的是能够在ng-repeat中使用函数类,如下所示。
<div ng-controller="ProfilingCtrl as profileData">
<div ng-reapeat="x in profileData.getData()">
{{x[0]}}
</div>
</div>
getData()是一个返回字符串数组的函数。这甚至可能吗?如果没有,那么如何进行这样的操作呢?
答案 0 :(得分:3)
您的问题很有可能来自ng-reapeat
- &gt;拼写错误应为ng-repeat
。仍在帮助您使用代码:
如果您共享控制器代码,那将非常有用。但我会做点什么。
首先,除非您尝试在数据数组中显示每个字符串的第一个字符,否则删除[0],因为x表示迭代产生的元素。
<div ng-controller="ProfilingCtrl as profileData">
<div ng-repeat="x in profileData.getData()">
{{x}}
</div>
</div>
进一步建议:将数据绑定到变量而不是函数。 ES6风格(虽然我仍然坚持使用控制器的功能)
class MyController {
constructor(myDataService) {
this.myDataService = myDataService;
this.myData = []; // This is where the data will be
}
handleError(error) {
// do something error
}
getData() {
this.myDataService.getData() // this is some method that returns a promise
.then(response => this.myData = response) // response from http in a promise
.catch(error => this.handleError(error));
}
$onInit() { // angular will take care of starting this off
this.getData();
}
}
注意当组件准备好时,Angular会调用$ onInit。阅读生命周期钩子:https://toddmotto.com/angular-1-5-lifecycle-hooks
生命周期钩子超出了你的问题的范围,但仍然很好进入。
请注意,不建议先前发表的关于“将其绑定到$scope
”的注释。您正在做的控制器更好,以后可以放在其他地方。