I'm building an Angular library that provides a bunch of components that should make it easier to build SPA application on top of a certain API. For some components we're using the multi-slot transclusions feature. Multi-slot transclusions and components were introduces in the AngularJS 1.5 release.
I really like both features, but I don't understand why components always have an isolated scope. I would like to control how variables are accessible in my transcluded template. But now I can't, because I can't control the scope. This basically means I have to tell the users of my library to reference the parent scope first in order to get to the data they need.
Does anyone know a workaround?, or maybe I'm doing it wrong. Then please tell me :-)
So this is my component:
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 )
...
Here's the template 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>
And this is how it can be used. And you see my problem. The expression must begin with $parent.$product.title, because the component scope is contained.
<product-list list="search.products">
<product-list-item-template>
<h2>{{$parent.$product.title}}</h2>
</product-list-item-template>
</product-list>
The simple answer is, that using parent scope is an issue when it comes to maintainability and reusability.
Angular 2 promotes the component pattern which requires to make all outer dependencies explicit. The angular 1 component function is the way to structure your application for easier migration to angular 2.
This post is a great reference if you are interested in details about the reasons: http://teropa.info/blog/2015/10/18/refactoring-angular-apps-to-components.html#replace-ng-controller-with-component-directive
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With