angularjs - 为什么 Angular (1.5) 组件总是有一个独立的作用域?

标签 angularjs angularjs-scope

我正在构建一个 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>

最佳答案

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

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

关于angularjs - 为什么 Angular (1.5) 组件总是有一个独立的作用域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35771690/

相关文章:

javascript - $scope 应该附加什么方法?

angularjs - 当选定的 ng-option 更改时获取值

angularjs - 使用 Angularjs 强制 "soft"更新字段

java - 如何为 CORS 指定响应 header ?

javascript - Froala 文本编辑器插入和删除自定义 html 标签

javascript - Angular $compile on scope with ng-repeat 不起作用

javascript - Angularjs:一个在 Controller 之间共享数据的工厂

javascript - 我可以使用 Angular JS ng-repeat 和 Turn.js 吗?

javascript - 使用 ng-style 更改输入占位符的颜色

javascript - 从表单输入生成对象