$ compile()不会在自定义Angular指令中触发

时间:2015-02-25 18:55:00

标签: angularjs angularjs-directive angularjs-scope

我有以下指令:

angular.module("example_module", [])
.directive("example_directive", function() {
  return {
    compile: function(element) {
      element.html('{{example}}');
      return function($scope) {
        $scope.example = "Hello world";
      };
    }
  };
});

以及以下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 example_directive></div>
  </body>
</html>

我希望该指令编译为Hello world,但它会编译为空字符串。错误在哪里?

我可以使用templatelink函数,但我的目标是了解compile函数的工作原理。

1 个答案:

答案 0 :(得分:1)

这与角度处理指令名称的方式有关。我已经更改了您的示例以匹配angular的命名约定并将Plunk

组合在一起
angular.module("example_module", [])
.directive("exampleDirective", function() {
  return {
    compile: function(element) {
      element.html('{{example}}');
      return function($scope) {
        $scope.example = "Hello world";
      };
    }
  };
});

<body>
    <div example-directive></div>
</body>