Angular 指令 compile() 函数如何访问隔离范围?

How can an Angular directive compile() function access an isolated scope?

我有以下指令:

angular.module("example_module", [])
.directive("mydirective", function() {
  return {
    scope: { data: "@mydirective" }
    compile: function(element) {
      element.html('{{example}}');
      return function($scope) {
        $scope.example = $scope.data + "!";
      };
    }
  };
});

和以下 HTML 代码:

<!DOCTYPE html>
<html ng-app="example_module">
  <head>
    <meta charset="utf-8">
    <title>Example title</title>
    <script src="lib/angular/angular.min.js"></script>
    <script src="js/example.js"></script>
  </head>
  <body>
    <div mydirective="Hello world"></div>
  </body>
</html>

我希望该指令编译为 Hello world!,但它编译为一个空字符串。 scope 创建了一个孤立的范围,似乎无法达到 {{example}}

我想知道 compile() 创建的新 HTML 代码如何访问 link 函数 $scope

这是行不通的,因为 {{example}} 正在根据父范围进行评估,这是有道理的,因为您实际上是在编译之前将元素更改为:

<div>{{example}}<div>

您可以通过将“$scope.example =”替换为“$scope.$parent.example =”来进行验证(仅用于演示目的 - 使用 $parent 不是最佳做法)。

你真正想做的是类似于嵌入的东西,但有更简单的方法可以做到。例如:

angular.module("example_module", [])
.directive("mydirective", function() {
  return {
    restrict: 'A',
    scope: { data: "@mydirective" },
    template: '{{example}}',
    compile: function(element) {
      return function($scope) {
        console.log($scope.data);
        $scope.example = $scope.data + "!";
        console.log($scope.example);
      };
    }
  };
});

当您使用模板时,它会替换指令所应用到的元素的内容(除非您使用 replace: true,在这种情况下它会替换整个元素),并且会根据模板的内容进行评估指令范围。

您可以使用传递给编译 (see the docs) 的 transclude 参数来做您想做的事情,但这已被弃用,所以我不建议走那条路。

Here's a Plunk 您可以在其中进行一些变奏。