【发布时间】:2016-06-16 18:00:27
【问题描述】:
我正在构建一个 Angular 库,它提供了一堆组件,应该可以更轻松地在某个 API 之上构建 SPA 应用程序。对于某些组件,我们正在使用多槽嵌入功能。 AngularJS 1.5 版本中引入了多槽嵌入和组件。
我真的很喜欢这两个功能,但我不明白为什么组件总是有一个孤立的范围。我想控制如何在我的嵌入模板中访问变量。但现在我不能,因为我无法控制范围。这基本上意味着我必须告诉我的库的用户首先引用父范围才能获取他们需要的数据。
有人知道解决方法吗?或者我做错了。那么请告诉我:-)
这是我的组件:
export const ProductsListComponent =
{
transclude: {
'template' : '?productListItemTemplate'
},
templateUrl: 'app/components/products-list/products-list.html',
controller: ProductsListComponentController,
bindings: {
list: '='
}
}
...
angular.module('MyWebApplication', ['ngMessages', 'ui.router' ])
.component( 'productList', ProductsListComponent )
...
这是模板 HTML:
<div class="product-list-wrapper" ng-repeat="$product in $ctrl.list">
<ng-transclude ng-transclude="template">
<product-list-item product="$product"></product-list-item>
</ng-transclude>
</div>
这就是它的使用方式。你看到了我的问题。表达式必须以 $parent.$product.title 开头,因为包含组件范围。
<product-list list="search.products">
<product-list-item-template>
<h2>{{$parent.$product.title}}</h2>
</product-list-item-template>
</product-list>
【问题讨论】: