javascript – Angular ng-click无法使用$compile
作者:互联网
我有类似于以下代码的代码来触发Angular应用程序中的单击事件.为什么事件不会触发?
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>
标签:javascript,angularjs,angularjs-directive,angularjs-ng-click 来源: https://codeday.me/bug/20190528/1168325.html