Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a binding to transcluded scope in component

In AngularJS 1.5, I want to pass a binding from a component into the (multi-slot) transcluded scope - for a reference in the template (in either one specific or all of them - no either way is fine).

This is for creating a generic custom-select list

// Component
.component('mySelect', { 
   bind: { 
       collection: '<'
   },
   transclude:{
      header: 'mySelectHeader',
      item: 'mySelectItem'
   },
   templateUrl: 'my-select-template',
   controller: function(){
       ..... 
   }
});

...
// Component template
<script id="my-select-template" type="text/ng-template">
<ol>
  <li ng-transclude="header"> </li>
  <li ng-transclude="item"
      ng-click="$ctrl.select($item)"
      ng-repeat"$item in $ctrl.collection">
  </li>
</ol>
</script>

...
// Example usage
<my-select collection="[{id: 1, name: "John"}, {id: 2, name: "Erik"}, ... ]>
   <my-select-head></my-select-head>

   <!-- Reference to $item from ng-repeate="" in component  -->
   <my-select-item>{{$item.id}}: {{$item.name}}</my-select-item>

</my-select>

Is this possible from a .component()? with custom-directives for the transclusion ?

like image 622
Chris2402 Avatar asked Sep 19 '16 13:09

Chris2402


1 Answers

In your parent component my-select keep a variable like "selectedItem"

In your child component my-select-item, require your parent component like below

require: {
  mySelect: '^mySelect'
}

And in your my-select-item component's controller, to access your parent component

 $onInit = () => {
  this.mySelectedItem= this.mySelect.selectedItem; // to use it inside my-select-item component.
 };
 select($item) {
   this.mySelect.selectedItem = $item; // to change the selectedItem value stored in parent component
 }

So that the selected item is now accessible from

<my-select-item>{{selectedItem.id}}: {{selectedItem.name}}</my-select-item>
like image 182
Salih Şenol Çakarcı Avatar answered Oct 04 '22 03:10

Salih Şenol Çakarcı