$sce in angular

27 / Apr / 2014 by Sakshi Tyagi 0 comments

In my Angular project, I came across a situation where i had to render some html markup, but the tricky thing was, the markup was contained in some angular scope variable. And when outputting it, it just printed out the html markup as basic text.

A quick Google search informed me about the directive ng-bind-html and ng-bind-html-unsafe, but the markup would still not render.

The problem was that, from Angular 1.2, in order to allow us to use ng-bind-html, we have to use an angular provided service “$sce”, which surely solved my problem.

“Strict Contextual Escaping” abbreviated as “sce” is a service of angular, which helps us to safely bind the values in our angular application. One such example can be of HTML binding. Lets consider example from my project:

Controller code (controller.js):

$http.get('/api/work/get?workId=' + $routeParams.workId).success(function (work) {
      $scope.currentWork = work;
    });

Html code:

<p> {{currentWork.description}}</p>

Here, “currentWork.description” may contain some html markup like: <b>this is demo description</b><br/> and this is new line.

Now when the html page is rendered, it displays description content as it is: <b>this is demo description</b><br/> and this is new line.

To execute this and render it as html, we have to tell angular that its secure to bind this. It can be done using $sce.trustAsHtml(). This method converts the value to privileged one that is accepted and rendered safely by using “ng-bind-html”.

We have to pass “$sce” service to our controller:

controller('transferWorkStep2', ['$scope','$http','$routeParams','$sce', function ($scope,$http, $routeParams, $sce) {
    $http.get('/api/work/get?workId=' + $routeParams.workId).success(function (work) {
      $scope.currentWork = work;
      $scope.currentWork.description = $sce.trustAsHtml($rootScope.currentWork.description);
    });

Html code:
<p ng-bind-html="currentWork.description"></p>

It will display :
this is demo description
and this is new line

So, this is how we can use “$sce” to make scope values content trusted.

FOUND THIS USEFUL? SHARE IT

Leave a comment -