mccainz mccainz - 5 months ago 30
AngularJS Question

Using HTML Entities within Angular strings

Given a string in my $scope model which contains an HTML entity, how do I ensure that the entity is properly displayed as an HTML character rather than a literal string?

HTML entity - MDN Glossary

http://plnkr.co/edit/0BliljcDkj0vvj3jdEqz?p=preview

<!DOCTYPE html>
<html>

<head>
<script data-require="angular.js@*"
data-semver="1.2.13"
src="http://code.angularjs.org/1.2.13/angular.js"></script>

</head>

<body>
<div ng-controller="htmlChar">{{title}}</div>

<script>

angular.element(document).ready(function(){

var app=angular.module("app",[]);
app.controller("htmlChar",function($scope){
$scope.title = "&copy; Acme";
});
angular.bootstrap(document, ['app']);

});

</script>

</body>
</html>

Answer

With $sce. You need to explicitely tell angular the content is html.

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

<script>

  angular.element(document).ready(function(){

    var app=angular.module("app",[]);
    app.controller("htmlChar",function($scope, $sce){
      $scope.title = $sce.trustAsHtml("&copy; Acme");
    });
    angular.bootstrap(document, ['app']);

  });

</script>

http://plnkr.co/edit/9iNnRC7AxFptnQZLPtYR?p=preview

Comments