我有一个名为 edResults 的父组件。该组件负责从 API 中提取数据并将数据显示在表格中。
该表的一部分是一个名为 profileImageScroller 的子组件。该组件负责在自定义滚动条组件中输出个人资料图像。
我试图将个人资料图像作为数组从 edResults 传递到 profileImageScroller,但没有成功。由于某种原因 profileImageScroller 看不到图像数组。
以下是我的代码的相关部分:
edResults.html:
<img src="{{$ctrl.images[0]}}"> <!--This does work and outputs first image-->
<profile-image-scroller images="$ctrl.images"></profile-image-scroller>
profileImageScroller.js:
(function () {
angular.module("brrrp").component('profileImageScroller', {
bindings: {
images : '<'
},
templateUrl: 'controls/profileImageScroller/profileImageScroller.html',
controller: profileImageScrollerController
});
function profileImageScrollerController() {
console.log(this.images); //this line is reached but this.images is empty
}
})();
为什么子组件没有收到父组件传递过来的图像数组?
最佳答案
绑定(bind)在 $onInit
Hook 内可用。我认为在此之前,绑定(bind)尚未链接。因此,应该执行以下操作:
app.component('profileImageScroller', {
bindings: {
images: '<'
},
templateUrl: '...',
controller: function() {
this.$onInit = function() {
console.log(this.images);
}
}
});
您可以阅读更多相关信息at the docs :
$onInit()
- Called on each controller after all the controllers on an element have been constructed and had their bindings initialized. This is a good place to put initialization code for your controller.
关于javascript - 在 AngularJS 中将数组从父组件传递到子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43896181/