Ole Albers
Ole Albers

Reputation: 9305

Binding Controller Property containing HTML in AngularJS

First of all: I am absolutely new to AngularJS but worked on MVC-projects in other languages.

I try to bind a Property containing HTML.

This is the code:

HTML:

<div ng-controller="MyController">
<p>{{About}}</p>
</div>

JS:

.controller('MyController', ['$scope', function($scope) {
$scope.About="This is me<br/>and not you!"
}

Now the HTML is encoded which I do not want (the <br/> should result in line breaks)

I already tried <p ng-bind-html="About"></p> but that resulted in no output at all

Upvotes: 0

Views: 79

Answers (3)

mccainz
mccainz

Reputation: 3497

You need to allow html in your text which Angular does not by default.

Plunker: http://plnkr.co/edit/K4KRCQi4Rpe99MJel5J2?p=preview

Angular Docs for $sce

Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain contexts to result in a value that is marked as safe to use for that context. One example of such a context is binding arbitrary html controlled by the user via ng-bind-html. We refer to these contexts as privileged or SCE contexts.

<div ng-controller="htmlChar" ng-bind-html="about"></div>

<script>

  angular.module("app",[])
  .controller("htmlChar",function($scope, $sce){
     $scope.about= $sce.trustAsHtml("This is me<br/>and not you!");
  });

  angular.bootstrap(document,["app"]);

</script>

Upvotes: 2

Geo Jacob
Geo Jacob

Reputation: 6009

You have to use angular compile functionality here, go through the link to get more information angular compile

Upvotes: 0

Roberto Linares
Roberto Linares

Reputation: 2225

You shoudln't need to insert html through model binding in AngularJS since the philosophy of the framework is to keep the HTML (page's structure and style) intact and only bind the data to be shown inside that HTML.

If you really need to bind HTML tags into your data you need to use the $sanitize service.

Upvotes: 1

Related Questions