【发布时间】:2020-09-01 13:48:49
【问题描述】:
假设我构建了一个 AngularJS 组件
function FooController($scope, $element, $attrs, $http) {
var ctrl = this;
ctrl.bar = "WIBBLE";
}
angular.module("app").component("foo", {
templateUrl: "/app/components/foo.html",
controller: FooController,
transclude: true
}
使用这样的模板,其中包含带有后备内容的嵌入标签
[<ng-transclude>{{$ctrl.bar}}</ng-transclude>]
我在这样的页面中使用它
<foo></foo>
然后后备内容在控制范围内执行,我得到了这个
[WIBBLE]
但如果我通过嵌入提供相同的东西
<foo>{{$ctrl.bar}}</foo>
然后嵌入的内容有一个新的隔离范围,$ctrl.bar 没有解析,所以我得到了
[]
如何设置合适的范围?
对于指令,我将定义 link 函数并使用 transclude 函数设置范围,但 component 不支持 link 函数,所以我不能这样做。
Why do Angular (1.5) components always have an isolated scope? 表明这完全不可能,答案是改用指令。如果是这样,我不确定组件的意义是什么。
【问题讨论】:
标签: angularjs-scope angularjs-components