Exploring the world of Angular directives, I am attempting to create a directive that can generate dynamic HTML elements. Let's take a look at the following code snippet:
<body ng-app="myApp" ng-controller="myCtrl">
<my-directive></my-directive>
</body>
The desired outcome would be:
<span>My HTML<span>
Accompanied by this CSS style:
span {
color:blue;
}
Here is my directive implementation:
myApp.directive("myDirective", ['$sce', function($sce) {
return {
restrict: "E",
scope: {
text: "="
},
template: '{{test}}',
replace: true,
transclude: false,
link: function(scope, element, attrs) {
scope.test = "<span>My HTML<span>";
}
}
}]);
I have made multiple attempts but none have been successful. You can view my CodePen example. Any help or guidance on what I may be missing would be greatly appreciated. I suspect it could be related to using HTML content, so I attempted to utilize $sce without success.
Edit: I have also added CSS styling for the span tag. Once everything works, the text should appear in blue color.