2

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.

1
  • Given working sample below, please refer Commented Nov 10, 2016 at 6:21

4 Answers 4

5

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

Sign up to request clarification or add additional context in comments.

Comments

3

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>

Comments

2
<html>
    <div
      ng-bind-html="myHTML">
    ...
    </div>
<html>

Ng Code :

angular.module('bindHtmlExample', ['ngSanitize'])
    .controller('ExampleController', ['$scope', function($scope) {
      $scope.myHTML =
         'I am an <code>HTML</code>string with ' +
         '<a href="#">links!</a> and other <em>stuff</em>';
    }]);

Download sanitize.js from here

Comments

1

AngularJS

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

HTML

<div ng-bind-html="string"> </div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.