简体   繁体   中英

Passing array from parent component to child component in AngularJS

I have a parent component called edResults. This component is responsible for pulling data from an API and displaying the data in a table.

Part of the table is a child component called profileImageScroller. This component is responsible for outputting the profile images in a custom scroller component.

I am trying to pass the profile images as an array from edResults to profileImageScroller, but with no luck. For some reason profileImageScroller does not see the image array.

The following are the relevant parts of my code:

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
}
})();

Why does the child component not receive the image array as passed from the parent component?

Bindings get available inside the $onInit hook. Before that, bindings haven't been linked I think. Hence, the following should do it:

app.component('profileImageScroller', {
  bindings: {
    images: '<'
  },
  templateUrl: '...',
  controller: function() {
    this.$onInit = function() {
      console.log(this.images);
    }
  }
});

You can read more about it 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM