I need help with dynamically loading my custom directive when a button is clicked. I am making an AJAX call to retrieve the directive's HTML and then compiling the response to assign it to a controller scope variable. However, the corresponding template of the custom directive is not displaying correctly. Can someone assist me with this issue?
Below is the code snippet that demonstrates the problem:
HTML file:
<body ng-app="sampleApp" ng-controller="DemoController as DemoCtrl">
<div ng-bind-html="test">
<md-button class="md-raised md-primary" ng-click="DemoCtrl.getDirective()">Click to get directive</md-button>
</body>
Module and Controller/Directive:
angular.module('sampleApp',['ngMaterial'])
.directive('test',function(){
return {
restrict: 'E',
template: '<B>Hello World</B>'
};
})
.controller('DemoController', function($compile,$scope,$sce) {
var vm = this;
vm.getDirective = function(){
//Service call to retrieve the directive HTML (e.g., <test></test>)
var directiveCode = $compile("<test></test>");
var directiveHTML = directiveCode($scope);
$scope.test = $sce.trustAsHtml(directiveHTML);
$scope.$apply();
}
});