I have code similar to the below code to trigger a click
event in an Angular app. Why is not the event triggering?
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!');
};
}
}
})
Change your compile statement like this:
$compile(element.contents())(scope);
You were passing a DOM string childElement
which is really not a DOM element instead it is a string. But the $compile
needs the DOM element(s) to actually compile the content.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With