假设我构建了一个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?表示完全不可能,答案是使用指令。如果是这样,我不确定组件的作用是什么。
提供将指令范围提供给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());
});
},