【问题标题】:How to set scope for AngularJS component如何设置 AngularJS 组件的范围
【发布时间】: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


    【解决方案1】:

    你只是不能为一个组件做到这一点。将其重构为指令,并提供一个链接函数,将指令范围提供给 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());
                });
            },
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-03
      • 2015-10-28
      • 1970-01-01
      • 2018-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多