为什么Angular(1.5)组件始终具有隔离范围? [英] Why do Angular (1.5) components always have an isolated scope?

查看:59
本文介绍了为什么Angular(1.5)组件始终具有隔离范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个Angular库,该库提供了一堆组件,这些组件应该使在某个API之上构建SPA应用程序更加容易.对于某些组件,我们正在使用多插槽包含功能.AngularJS 1.5版本中引入了多槽包含和组件.

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 :-)

这就是我的组件:

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开头,因为包含了组件范围.

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提升了组件模式,该模式要求使所有外部依赖关系明确.角度1组件功能是构建应用程序以更轻松地迁移到角度2的方式.

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

这篇关于为什么Angular(1.5)组件始终具有隔离范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆