将绑定传递到组件中的嵌入范围 [英] Passing a binding to transcluded scope in component

查看:21
本文介绍了将绑定传递到组件中的嵌入范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 AngularJS 1.5 中,我想将一个组件的绑定传递到(多槽)内嵌作用域中 - 用于模板中的引用(在一个特定的或所有这些中 - 没有任何一种方式都可以).

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>

这可能来自 .component() 吗?带有 transclusion 的自定义指令?

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

推荐答案

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

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

在你的子组件 my-select-item 中,像下面这样需要你的父组件

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

require: {
  mySelect: '^mySelect'
}

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

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>

这篇关于将绑定传递到组件中的嵌入范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆