我正在構建一個Angular庫,它提供了一堆組件,這些組件可以更容易地在特定的API之上構建SPA應用程序。對於某些組件,我們正在使用多插槽轉換功能。多槽插件和組件在AngularJS 1.5版本中引入。爲什麼Angular(1.5)組件總是有一個孤立的範圍?
我真的很喜歡這兩個功能,但我不明白爲什麼組件總是有一個孤立的範圍。我想控制如何在我的transcluded模板中訪問變量。但現在我不能,因爲我無法控制範圍。這基本上意味着我必須告訴我的庫的用戶首先引用父範圍,以便獲取他們所需的數據。
有誰知道解決方法?或者我做錯了。那麼請告訴我:-)
所以這是我的組件:
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>
,這是它如何被使用。你看到我的問題。表達式必須以$父母開頭。 $ product.title,因爲包含組件範圍。
<product-list list="search.products">
<product-list-item-template>
<h2>{{$parent.$product.title}}</h2>
</product-list-item-template>
</product-list>
權。但是這感覺就像一個捕獲 - 22。我想使用組件模式來爲Angular 2做準備,但基本上看起來我只能在現在使用指令時達到我的目標,而不是真正的Angular 2。 – user3270137
我認爲應該有一種方法來將現有組件拆分爲幾個組件,並通過將所需的值傳遞給子組件將其移除。這有任何意義嗎? –
我想我可以重構在transclusion模板中的ng-repeat。但我的圖書館的目標是抽象所有的API調用我的最終用戶。 如果有一種方法可以將$ product綁定到模板,那麼這將是最優雅的解決方案。但我想這隻能用編譯方法中的指令完成。 – user3270137