Display string containing HTML tag in Angular

Fred A picture Fred A · Nov 10, 2016 · Viewed 9k times · Source

I checked for answers in SO but couldn't find satisfying answer. So here I'm asking :

I have a string as follow

var string = "With this you have agreed with the <a href='#'>rules and condition</a>"

Which I need to render as both string (for the text portion) and HTML (for the HTML portion).

How do I achieve this in AngularJs? I tried with $compile but it didn't work for me, it output chunks of seemingly minified code on the page.

Answer

Sajeetharan picture Sajeetharan · Nov 10, 2016

You can do this using ng-bind-html,

angular.module('myapp', ['ngSanitize'])
.controller('foo', function($scope) {
    $scope.bar = "With this you have agreed with the <a href='#'>rules and condition</a>";
});

<div ng-controller="foo">    
    <div ng-bind-html="bar"></div>    
</div>

DEMO