SoFunction
Updated on 2025-04-12

Deeply understand the ng-bind-html directive and $sce service in AngularJS

Preface

One of the power of Angularjs is its powerful data bidirectional binding feature. Two things we often use are ng-bind and ng-model for form.

But in our project, we will encounter this situation, the data returned in the background contains various html tags.

like:

$ = “hello,<br><b>Where will we go today?</b>”

We use instructions like ng-bind-html to bind, but the result is not what we want.

That's it

hello,
Where will we go today?

What to do?

For the angular version 1.2, we must use the $sce service to solve our problem. The so-called sce is the abbreviation of "Strict Contextual Escaping". Translated into Chinese is "strict context mode" and can also be understood as safe binding.

Let's see how to use it.

controller code:

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

HTML code:

<p> {{}}</p>

The content we return contains a series of html tags. The results are shown as we said at the beginning of the article. At this time we must tell it to bind safely. It can be used$ () . This method converts the value to privileged acceptance and uses "ng-bind-html" safely. So, we have to introduce $sce service in our controller

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

html code:

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

This result is perfectly presented on the page:

hello 
Where will we go today?

We can also use it like this, encapsulate it into a filter and call it on the template at any time.

('to_trusted', ['$sce', function ($sce) {
return function (text) {
 return $(text);
};
}]);

html code:

<p ng-bind-html=" | to_trusted"></p>

Summarize

The above is all about the ng-bind-html directive and $sce service in AngularJS. I hope it will help you study or work. If you have any questions, you can leave a message to communicate.