angularjs - 将绑定(bind)传递到组件中的嵌入范围

标签 angularjs angularjs-directive angularjs-scope web-component transclusion

在 AngularJS 1.5 中,我想将一个绑定(bind)从组件传递到(多槽)嵌入范围 - 作为模板中的引用(在一个特定的或所有模板中 - 没有任何一种方法都可以)。

这是为了创建通用的自定义选择列表

// 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() 实现吗?使用嵌入的自定义指令?

最佳答案

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

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

require: {
  mySelect: '^mySelect'
}

并在 my-select-item 组件的 Controller 中访问您的父组件

 $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
 }

现在可以从以下位置访问所选项目

<my-select-item>{{selectedItem.id}}: {{selectedItem.name}}</my-select-item>

关于angularjs - 将绑定(bind)传递到组件中的嵌入范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39574792/

相关文章:

angularjs - 访问 Controller 内的 AngularJs 指令变量

javascript - 避免在数据表中呈现 "No Data Available in the table"

javascript - ngRepeat 中的第一个 ngModel 被分配了自定义指令

javascript - 从指令 angularjs 中给出 highchart 正确的参数

javascript - 具有动态选择字段的表单无法验证

javascript - angularjs:ng-click <a> 不工作,适用于 <button>

javascript - Angular 指令 - 添加指令后范围中断

javascript - 使用 Spring mvc 和 Angular JS 显示数据库中的图像列表

angularjs - ionic - $state.go 存在参数问题

javascript - AngularJs:具有多个语句的 ngClass