如何设置AngularJS组件的作用域

问题描述 投票:0回答:1

假设我构建了一个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
1个回答
0
投票

提供将指令范围提供给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());
            });
        },
© www.soinside.com 2019 - 2024. All rights reserved.