【问题标题】:Why do Angular (1.5) components always have an isolated scope?为什么 Angular (1.5) 组件总是有一个孤立的范围?
【发布时间】: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>

【问题讨论】:

    标签: angularjs angularjs-scope


    【解决方案1】:

    简单的答案是,在可维护性和可重用性方面,使用父作用域是一个问题。

    Angular 2 促进了组件模式,它需要明确所有外部依赖项。 angular 1 组件函数是构建应用程序以便更容易迁移到 angular 2 的方式。

    如果您有兴趣详细了解原因,这篇文章是一个很好的参考:http://teropa.info/blog/2015/10/18/refactoring-angular-apps-to-components.html#replace-ng-controller-with-component-directive

    【讨论】:

    • 对。但这感觉像是第 22 条规则。我想使用组件模式为 Angular 2 做准备,但基本上看起来我现在只能在使用指令时实现我的目标,而不是真正的 Angular 2 方式。
    • 我认为应该有一种方法可以将现有组件拆分为多个组件,并通过将所需值传递给子组件来消除嵌入。这有意义吗?
    • 我想我可以重构嵌入模板中的 ng-repeat。但是我的库的目标是为我的最终用户抽象出所有 API 调用。如果有办法将 $product 绑定到模板,那将是最优雅的解决方案。但我想这只能通过编译方法中的指令来完成。
    猜你喜欢
    • 1970-01-01
    • 2015-12-28
    • 2017-12-16
    • 1970-01-01
    • 2018-08-27
    • 2012-11-07
    • 2011-04-28
    • 2015-12-15
    • 2017-01-02
    相关资源
    最近更新 更多