I am trying to build the following directive for a simple modal window who's usage would be as follows:
<modal content="<div class='error-text'>this is the content</div>"></modal>
Which should generate the following markup:
<div class="modal-wrap fade-hide fade-show" ng-show="showModal" ng-click="showModal=false">
<div class="modal-info clearfix" ng-click="$event.stopPropagation()">
<div class='error-text'>this is the content</div>
<button class="btn form-control" ng-click="showModal=false">OK</button>
</div>
</div>
Here is my directive so far:
.directive('modal', function($compile){
return {
restrict: 'AE',
replace: true,
link: function(scope, element, attrs) {
scope.content = attrs.content;
},
template: '<div class="modal-wrap fade-hide fade-show" ng-show="showModal" ng-click="showModal=false"><div class="modal-info clearfix" ng-click="$event.stopPropagation()">{{content}}<button class="btn form-control" ng-click="showModal=false">OK</button></div></div>',
};
})
The problem I am having is that the {{content}} is not being compiled. It is being rendered as literal html.
And my modal window looks like this:
How do I configure my directive such that the content
attribute is compiled as HTML?
In this sample i used bootstrap for our modal.
Remember: in the directive you can use scope instead Attr it's much better.
for binding Html in your directive or everywhere use ng-bind-html as this sample
index.html
<modal content="<div class='alert alert-danger'>this is the content</div>"></modal>
modal.html
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body" ng-bind-html="content | trust">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
filter
This filter helps you to bind html as trust codes, we use it in the modal.html on ng-bind-html attribute.
app.filter("trust", ['$sce', function ($sce) {
return function (htmlCode) {
return $sce.trustAsHtml(htmlCode);
}
}]);
directive
app.directive('modal', function () {
return {
restrict: 'AE',
templateUrl: "modal.html",
scope: {
content: "@"
},
link: function (scope, element, attrs) {
$('#myModal').modal('show');
}
};
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.