Slartibartfast
Slartibartfast

Reputation: 1623

How can I enter text and render the html using angularjs?

I want to bind a text box to an angularjs variable and have it output rendered html in a separate div.

I have:

<div ng-app="myapp">
<form:textarea ng-model="ddata" id="displayData" path="displayData"/>

<div ng-bind-html-unsafe='ddata'>
{{ddata}}
</div></div>

and all I see is "{{ddata}}"

I would like to type in something like: 'b bold text /b>

and have it render bold text.

If someone could post a fiddle, I would appreciate it greatly.

Upvotes: 3

Views: 9470

Answers (1)

shaunhusain
shaunhusain

Reputation: 19748

Version that works in angular < 1.2

http://jsfiddle.net/AQWAR/

The HTML

<div ng-app="myapp">
<form>
    <input type="text" ng-model="ddata"/>
</form>
{{ddata}}

<div ng-bind-html-unsafe='ddata'>
</div>
</div>

The JS

angular.module("myapp", []);

Version that works in Angular > 1.2 (specifically tested with 1.2.1)

http://jsfiddle.net/AQWAR/1/

HTML

<div ng-app="myapp" ng-controller="MyCtrl">
<form>
    <input type="text" ng-model="ddata.someString"/>
</form>
{{ddata}}

<div ng-bind-html='ddata.trustedVersion'>
</div>
</div>

The JS

angular.module("myapp", []).controller("MyCtrl", ["$scope","$sce", function($scope, $sce){
    $scope.ddata = {someString:"", trustedVersion:""}
    $scope.$watch("ddata.someString", function(newVal){
        $scope.ddata.trustedVersion = $sce.trustAsHtml(newVal);
    },true);
}]);

For some safer options check out $sanitize and $sce

http://docs.angularjs.org/api/ngSanitize.$sanitize

http://docs.angularjs.org/api/ng.$sce

Upvotes: 11

Related Questions