I want to handle an onClick() event from generated by ng-bind-html.
I tried some ways but still didn't find a solution. Any help will be appriciated.
<html ng-app="Demo">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
<script>
angular.module('Demo', [])
.controller('MyController', ['$scope', '$sce', function($scope, $sce) {
$scope.memo = $sce.trustAsHtml('<a href="#" ng-click="close();">Binding html</a>');
$scope.close = function() {
alert("close clicked");
};
}]);
</script>
</head>
<body ng-controller="MyController">
<div><a href="#" ng-click="close();">No binding html</a></div> <!-- This is OK -->
<div ng-bind-html="memo"></div> <!-- My question is here. I can't call close() -->
</body>
</html>
Upadte 1
I think this question is relevant.
How to make ng-bind-html compile angularjs code
Update 2
Fixed it thanks to user2341963 but I'm not sure why it works...
<html ng-app="Demo">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
<script>
angular.module('Demo', [])
.directive('dynamic', function ($compile) {
return {
restrict: 'A',
replace: true,
link: function (scope, ele, attrs) {
scope.$watch(attrs.dynamic, function(html) {
ele.html(html);
$compile(ele.contents())(scope);
});
}
};
})
.controller('MyController', ['$scope', '$sce', function($scope, $sce) {
$scope.memo = $sce.trustAsHtml('<a href="#" ng-click="close();">Binding html</a>');
$scope.close = function() {
alert("close clicked");
};
}]);
</script>
</head>
<body ng-controller="MyController">
<div>
<a href="#" ng-click="close();">No binding html</a>
</div>
<div dynamic="memo"></div>
</body>
</html>