Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs component - transclusion with passing data

Tags:

angularjs

Hello I would like to create component with transclusion and passing data from child to parent component. My idea is here:

List component template:

<ul>
 <li ng-repeat="item in $ctrl.list"><ng-transclude></ng-transclude></li>
</ul>

Using

<list-component>
  <strong>{{itemFromComponent.name}}<strong>
  //how to get item from list-component to here??
</list-component>

Please show me how to pass current item from component to parent to be able to see it. Thanks

like image 672
bluray Avatar asked Oct 15 '25 18:10

bluray


1 Answers

Inside components, the ng-transclude directive adds a child scope.

To access the component scope, prepend transcluded variables with $parent:

<list-component list="[1,3,8]">
  LIST {{$parent.$ctrl.list}}<br/>
  ITEM <strong>{{$parent.item}}</strong>
</list-component>

The DEMO

angular.module("app",[])
.component("listComponent", {
  transclude: true,
  bindings: {list: '<'},
  template: `
 <ul>
  <li ng-repeat="item in $ctrl.list">
    $index={{$index}}<br/>
    <ng-transclude></ng-transclude>
  </li>
</ul>
`
})
<script src="//unpkg.com/angular/angular.js"></script>
  <body ng-app="app">
    <list-component list="[1,3,8]">
      LIST {{$parent.$ctrl.list}}<br/>
      ITEM <strong>{{$parent.item}}</strong>
    </list-component>
  </body>
like image 96
georgeawg Avatar answered Oct 17 '25 21:10

georgeawg