Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display string containing HTML tag in Angular

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.

like image 373
Fred A Avatar asked Jun 27 '26 06:06

Fred A


2 Answers

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

like image 59
Sajeetharan Avatar answered Jun 29 '26 20:06

Sajeetharan


You can use ng-bind-html directive as below. To use this, you have to include ngSanitize module and related js file.

var app = angular.module('app', ['ngSanitize']);

app.controller('TestController', function($scope) {
  $scope.string = 'With this you have agreed with the <a href="#">rules and condition</a>';
});

angular.bootstrap(document, ['app']);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-sanitize/1.5.8/angular-sanitize.min.js"></script>
<div ng-controller="TestController">
  <span ng-bind-html="string"></span>
</div>
like image 27
Aruna Avatar answered Jun 29 '26 20:06

Aruna