3

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.

3
  • Have you wired up the rest of your app? Commented Jul 22, 2013 at 18:03
  • How do you mean? As in, have I added the ng-app="myapp" directive to a containing div? Yes. I've also included the scripts for angular min and angular sanitized. Or is there something else? Commented Jul 22, 2013 at 18:04
  • 1
    You're missing your own JS that says angular.module("myapp", []) most likely Commented Jul 22, 2013 at 18:10

1 Answer 1

11

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

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

5 Comments

That's it. Thank you. I totally forgot the js.
Works with Angular 1.1.1, not 1.2.1.
Thanks Garry you're right with 1.2.1 you need to use ng-bind and $sce service to mark the data as trusted, I'll make an updated fiddle and update the answer.
@Garry updated the fiddle and the code above to reflect the changes needed. I used $sce to explicitly trust the input, in application this may not be a great idea since it could potentially allow someone to inject code that will be run in the browser (cross site scripting). So use with caution.
@shaunhusain Thanks for the update. $sce.trustAsHtml was the approach I took.

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.