I have a directive and I´m replacing IMG urls with img src to display images inline
function message($filter) {
var directive = {
restrict: 'EA',
scope: {
data: '='
},
link: function(scope, elem, attrs) {
scope.data.content = scope.data.content.replace(/(https?:\/\/\S+(\.png|\.jpeg|\.jpg|\.gif))/g, "<img src='$1' alt=''>");
},
template: '<span>{{data.nickname}}:</span> {{data.content}}'
};
return directive;
}
but instead of seeing the image inline I´m seeing the HTML tag as text I´m investigating $sce but I´m not sure how to use it inside a directive.
You are closer!. You are right about working with ngSanitize module.
It basically allows you to write raw HTML in your template (using ng-bind-html directive). You need to include it in your page, and declare it as a dependency in your module like this:
<!-- HTML -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-sanitize/1.6.2/angular-sanitize.min.js"></script>
// JavaScript
angular.module("yourapp", ['ngSanitize']);
And then, bind your HTML content in a div (or whatever) using ng-bind-html directive like this:
template: '<span>{{data.nickname}}:</span> <div ng-bind-html="data.content"></div>'
Now, the raw HTML contents of data.content will be replaced as is in your directive's template. Here is a working plunker for your reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With