Angular ng-click 不适用于 $compile

Angular ng-click not working with $compile

我有类似于以下代码的代码来触发 Angular 应用程序中的 click 事件。为什么事件没有触发?

var app = angular.module("myApp", [])

app.directive('myTop',function($compile) {
return {
    restrict: 'E',
    template: '<div></div>',
    replace: true,
    link: function (scope, element) {
        var childElement = '<button ng-click="clickFunc()">CLICK</button>';
        element.append(childElement);
        $compile(childElement)(scope);

        scope.clickFunc = function () {
            alert('Hello, world!');
        };
    }
}
})

像这样更改你的编译语句:

$compile(element.contents())(scope);

您传递的 DOM 字符串 childElement 实际上不是 DOM 元素,而是一个字符串。但是 $compile 需要 DOM 个元素来实际编译内容。

var app = angular.module("myapp", []);

app.directive('myTop', ['$compile',
  function($compile) {
    return {
      restrict: 'E',
      template: '<div></div>',
      replace: true,
      link: function(scope, element) {
        var childElement = '<button ng-click="clickFunc()">CLICK</button>';
        element.append(childElement);
        $compile(element.contents())(scope);

        scope.clickFunc = function() {
          alert('Hello, world!');
        };
      }
    }
  }
])
<html>

<body ng-app="myapp">
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
  <my-top></my-top>
</body>

</html>