如何为 AngularJS 组件设置范围



假设我构建了一个 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函数,所以我不能这样做。

为什么 Angular (1.5( 组件总是有一个隔离的作用域?这表明这是不可能的,答案是改用指令。如果是这样,我不确定组件的意义是什么。

您只是无法为组件执行此操作。将其重构为指令,并提供一个链接函数,该函数将指令范围提供给 transclude 函数。

transclude: true, // support <ng-transclude> in the template
link: function (scope, element, attrs, controller, transclude) {
var transclusionElement = element.find("ng-transclude");
transclude(scope, function (clone, scope) {
// link element parameter is a jQuery element
transclusionElement.html(""); // wipe the slate
transclusionElement.append(clone); // write the content
// DO NOT TRY TO BE CLEVER LIKE THIS
// transclusionElement.html(clone.html());
});
},

最新更新