Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

render HTML in angularJS 1.x

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.

like image 524
handsome Avatar asked Dec 12 '25 05:12

handsome


1 Answers

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.

like image 96
31piy Avatar answered Dec 14 '25 19:12

31piy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!