使用$ sce在Angular 1.3.9视图中显示HTML

时间:2021-07-15 18:07:30

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

我正在尝试在Angular视图中显示HTML字符串。

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.

经过一番研究,我偶然发现了ngSanitize。我尝试过,但它完全剥离了所有HTML代码,只留下原始文本。确实非常安全。实际上有点太多了。无论如何,ngSanitize现在已经过时了。

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

此SO帖子表明现在必须使用$ sce服务而不是ngSnitize。

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

根据这些不同的解决方案,我想出了以下内容:

HTML

HTML

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

JS

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.

让我烦恼的是$ sce服务应该是自v1.2以来Angular核心的一部分,而我正在使用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) ?

这里发生了什么?有没有人有一个明确的方法来在AngularJS视图中显示HTML(没有只留下原始文本的过滤器)?

1 个解决方案

#1


28  

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

#1


28  

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