I am working on a directive with a template that includes a scope variable named content
:
<div class="directive-view">
<span class="directive-header">My Directive</span>
<span ng-bind-html="content"></span>
</div>
In the following directive, I have set up a watch for changes to the content
variable and then compile the element's contents:
(function () {
"use strict";
angular
.module('myApp.myDirective', [])
.directive("myDirective", myDirective);
function myDirective($compile, $sce) {
return {
restrict: 'E',
scope: {
},
templateUrl:'../partials/directives/my-directive.html',
controller: function($scope) {
$scope.testAlert = function(msg) { alert(msg) };
},
link: function (scope, element, attrs, ctrl) {
scope.content = $sce.trustAsHtml('Initial value');
scope.$watch(attrs.content, function(value) {
element.html(value);
console.log("Content changed -- recompiling");
$compile(element.contents())(scope);
});
scope.content = $sce.trustAsHtml('<button ng-click="testAlert(\'clicked!\')">Click</button>');
}
};
}
})();
Although the directive renders the button
element, the testAlert()
function in the controller is not called when the button is clicked.
Furthermore, the callback for $watch
only triggers once after setting content
to 'Initial value'. It does not trigger again after changing content
to the button. I expected the callback to be triggered when attrs.content
changes its value.
Even after manually recompiling the element:
$compile(element.contents())(scope);
The testAlert
function still does not get executed when clicking on the button element.
How can I ensure that the element's contents are correctly recompiled so that the bindings work as intended?