javascript - 在 AngularJS 中将数组从父组件传递到子组件

标签 javascript angularjs arrays

我有一个名为 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/

相关文章:

javascript - 为什么我无法在 Bootstrap 导航中使用下拉菜单?

javascript - 何时在 AngularJS 中使用 PATCH 和 PUT

javascript - 缩小 Angular 不更新模板?

php - 检查数组是否包含 $_GET ['id' ]

arrays - 为什么这个用 C 编写的程序在比较输入和某些数组时不打印值 5?

javascript - Angular Ng-重复有序列表

javascript - 如何使用jquery或rails获取特定年份中所有星期的列表

javascript - 属性在装饰器中未定义

javascript - 无法更新 AngularJS 输入值

对整数数组进行排序时出现 java.lang.ArrayIndexOutOfBoundsException