繁体   English   中英

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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM