9

I'm trying to display an HTML string in my Angular view.

At first, I naively tried this :

<p>{{ad.text}}</p>

$scope.ad = { 'text' : '<a href="#">Link</a>'}; // Dynamically fetched, etc. This is just an example text

But this just displays <a href="#">Link</a> in the view, not : link.

After some research, I stumbled upon ngSanitize. I tried it, but it totally strips off all HTML code to leave just raw text. Pretty secure indeed. A bit too much, actually. Anyway, ngSanitize is now outdated.

This SO post indicates that now the $sce service has to be used instead of ngSnitize.

Following these various solutions, here is what I came up with :

HTML

<p ng-bind-html="htmlAdText"></p>

JS

$scope.ad = { 'text' : '<a href="#">Link</a>'};

$scope.htmlAdText = $sce.trustAsHtml($scope.ad.text);

But this error comes in the console :

ReferenceError: $sce is not defined

What bugs me is that the $sce service is supposed to be part of Angular's core since v1.2, and I'm using v1.3.9.

What's going on here? Does anyone have a definitive method to display HTML in an AngularJS view ( without filters that just leave the raw text) ?

Community
  • 1
  • 1
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63

1 Answers1

30

Don't forget to inject it into controller, for instance:

app.controller('mainCtrl', [ '$scope', '$sce', function($scope, $sce){
    $scope.ad = { 'text' : '<a href="#">Link</a>'};
    $scope.htmlAdText = $sce.trustAsHtml($scope.ad.text);
}]); //End Controller
Community
  • 1
  • 1
Samir Alajmovic
  • 3,247
  • 3
  • 26
  • 28
  • 1
    Damn it, was it that simple? So it's part of the core, but you also have to inject it? I'm not used to Angular enough yet. Thanks a lot. – Jeremy Thille Mar 04 '15 at 11:48
  • 2
    Yes, you have to manually inject it into the controller, which when you think about it, makes sense. Otherwise you would otherwise constantly be injecting all services into your controller, even those you don't use. This would just be bloating the controller for no reason other than not having to write it out explicitly, and being explicit and not bloating is preferable to being implicit and bloating in this case. – Samir Alajmovic Mar 04 '15 at 11:55
  • This example just saved my ass: thank you Samir Alajmovic! In my code the syntax was slightly different like: .controller('DingleheimersController', function ($scope, $sce, $compile, $filter, $http, $location, $route, $timeout, fetch) {, simply adding $sce into the function (,,,) list got this working so I can use $sce.trustAsResourceUrl. Having been thrown at an angular codebase without any AngJS training sure has been fun :-(... – Dinglemeyer NeverGonnaGiveUUp Jan 26 '17 at 16:49