我正在尝试创建一个角度作为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()是一个返回字符串数组的函数。这有可能吗?如果没有,那么如何去做这样的手术呢?
您的问题来自ng-reapeat
->错字的可能性很大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
不建议您早先对“将其绑定到”发表评论。虽然您做的ControllerA更好,但是以后可以放到其他地方。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句