AngularJS:如何在不通过多个$parent导航的情况下访问最顶层的范围

AngularJS: how to access the topmost scope without navigating via multiple $parent?

本文关键字:情况下 导航 parent 访问 范围 AngularJS      更新时间:2023-09-26

我知道有很多问题,但我无法在其中找到答案。
我有一个关于我的弹出窗口的指令,其中包含许多模板,

.HTML

<popup template="popupTemplate"></popup>

命令

app.directive('popup', function () {
  return {
    restrict: 'E',
    scope: {
      template: '='
    },
    link: function ($scope, $element, $attrs) {
      // do something on $scope.template
    }
  }
});

现在在另一个元素上,我定义了目标弹出窗口的模板名称

<button popup-template="upload-avatar"></button>

命令

app.directive('popupTemplate', function () {
  return {
    link: function ($scope, $element, $attrs) {
      $element.bind('click', function () {
        $scope.$parent.popupTemplate = $attrs.popupTemplate;
        $scope.$apply();
      });
    }
  }
});

问题:
当我单击嵌套指令中的元素时。因为我需要处理:

$scope.$parent.popupTemplate
$scope.$parent.$parent.popupTemplate

这不是一个好主意。我需要知道如何使用唯一的语法而不是多个$parent访问第一个父范围。

只需包装popupTemplate

<popup template="whatever.popupTemplate"></popup>

然后,您可以:

$scope.whatever.popupTemplate = $attrs.popupTemplate;

完全没有$parent。

假设你有父范围 A 和子范围 B。默认情况下,B 复制 A 中的所有值。此处的复制表示响应指针。

在爪哇中比较:

void bad(String s) {
    s = "new";
}
void good(String[] s) {
    s[0] = "new";
}