Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to bind html in angular v1.2

I was trying to make a blog in angularJS and on the post message section I want to get the message from json and add it to a content div like this

<div class="content">
    {{json.message}}
</div>

Now my div has a paragraph in it, it's practically a html code like this

<p>this is my message</p>

but when i do this, i see on the screen this

<p>this is my message</p>

as text. I understand in previous versions i could use ng-bind-html-unsafe but i am using v1.2 of angularJS. Can anyone please show me code similar to ng-bind-html-unsafe so that I can make this work in v1.2? Thank you, Daniel!

like image 606
Pacuraru Daniel Avatar asked Sep 12 '13 20:09

Pacuraru Daniel


2 Answers

You can use the Strict Contextual Escaping services ($sce) in 1.2

Controller:

function myCtrl($scope,$sce) {
    $scope.myHtml = $sce.trustAsHtml('<span>Hello World!</span>');
}

Template:

<div ng-app ng-controller="myCtrl">
    <div ng-bind-html="myHtml"></div>
</div>

Example: http://jsfiddle.net/TheSharpieOne/GKnrE/1/

like image 160
TheSharpieOne Avatar answered Sep 18 '22 07:09

TheSharpieOne


You'll need to inject and use the $sce service to mark it as trusted HTML, then use the ng-bind-html directive (plunkr):

app.js:

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

app.controller('MainCtrl', function($scope, $sce) {
  $scope.name = $sce.trustAsHtml('<p>Hello World</p>');
});

index.html:

<body ng-controller="MainCtrl">
    <div class="content" ng-bind-html="name"></div>
</body>
like image 27
Derek Stobbe Avatar answered Sep 20 '22 07:09

Derek Stobbe