gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 16:42:47 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com