将绑定传递给组件中的transcluded范围

Chr*_*402 9 web-component angularjs transclusion angularjs-directive angularjs-scope

在AngularJS 1.5中,我想将一个组件的绑定传递给(多槽)转换范围 - 用于模板中的引用(在一个特定的或全部的中 - 没有任何方法可以).

这用于创建通用自定义选择列表

// 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>
Run Code Online (Sandbox Code Playgroud)

这是可能的.component()吗?使用自定义指令transclusion?

Sal*_*rcı 5

在您的父组件中,my-select保留一个像"selectedItem"这样的变量

在您的子组件my-select-item中,需要您的父组件,如下所示

require: {
  mySelect: '^mySelect'
}
Run Code Online (Sandbox Code Playgroud)

在my-select-item组件的控制器中,访问您的父组件

 $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
 }
Run Code Online (Sandbox Code Playgroud)

这样就可以从中访问所选项目

<my-select-item>{{selectedItem.id}}: {{selectedItem.name}}</my-select-item>
Run Code Online (Sandbox Code Playgroud)