【问题标题】:Angularjs component - transclusion with passing dataAngularjs 组件 - 包含传递数据
【发布时间】:2018-05-17 04:10:02
【问题描述】:

您好,我想创建包含嵌入的组件并将数据从子组件传递到父组件。 我的想法在这里:

列表组件模板:

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

使用

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

请告诉我如何将当前项目从组件传递给父项以便能够看到它。谢谢

【问题讨论】:

  • 这甚至行不通。你有这个完全倒退。 list-component 没有single item,它有一个列表;您不能像这样将内部 HTML 嵌入到多个块中。换句话说,将ng-transclude 放入ng-repeat 是无效的。
  • ng-transclude inside ng-repeat 工作正常。但当然显示总是相同的数据。我认为它可能像在 angular2 中一样工作(在组件 &lt;ng-container *ngTemplateOutlet="template; context: {$implicit: d}"&gt;&lt;/ng-container&gt; 和父组件中:&lt;component&gt;&lt;ng-template #columnTemplate let-v let-data="data"&gt;&lt;/component&gt;
  • 是的,你说的是我的意思。 Angular 1.x 不会多次“扩展”嵌入,所以你总是得到相同的数据。在当前的 1.x 设计中,您不能根据内部模板数据进行多个嵌入。
  • 它不好。我想为从 API 加载数据的选择框创建通用组件,option 将从父级插入。现在我必须为每个数据源创建一个新组件。
  • 这与您在问题中询问的内容完全不同。选项列表与嵌入的 html 有什么关系?这开始感觉像是一个 xy 问题,你在问你的解决方案(嵌入)而不是你的问题。可能有一种方法可以实现你的目标,如果你问这个问题,并展示真实的代码示例,而不是......

标签: angularjs


【解决方案1】:

在组件内部,ng-transclude 指令添加了一个子作用域。

要访问组件范围,请在嵌入变量前添加$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>

【讨论】:

  • 唷,我花了一个小时寻找一个简洁的解决方案。非常感谢:-D
猜你喜欢
  • 2019-01-06
  • 2018-01-06
  • 2020-02-14
  • 2016-07-15
  • 2014-11-08
  • 1970-01-01
  • 2016-06-15
  • 2015-12-21
  • 2012-11-21
相关资源
最近更新 更多