我试图使用$sanitize提供者和ng-bind-htm-unsafe指令,以允许我的控制器将HTML注入DIV。

然而,我不能让它工作。

<div ng-bind-html-unsafe="{{preview_data.preview.embed.html}}"></div>

我发现这是因为它被从AngularJS中删除了(谢谢)。

但是如果没有ng-bind-html-unsafe,我就会得到这个错误:

http://errors.angularjs.org/undefined/预计美元/不安全


当前回答

而不是像Alex建议的那样在你的作用域中声明一个函数,你可以将它转换为一个简单的过滤器:

angular.module('myApp')
    .filter('to_trusted', ['$sce', function($sce){
        return function(text) {
            return $sce.trustAsHtml(text);
        };
    }]);

然后你可以这样使用它:

<div ng-bind-html="preview_data.preview.embed.html | to_trusted"></div>

这里有一个工作示例:http://jsfiddle.net/leeroy/6j4Lg/1/

其他回答

你不需要在ng-bind-html-unsafe中使用{{}}:

<div ng-bind-html-unsafe="preview_data.preview.embed.html"></div>

这里有一个例子:http://plnkr.co/edit/R7JmGIo4xcJoBc1v4iki?p=preview

{{}}操作符本质上只是ng-bind的简写,所以您尝试的是绑定中的绑定,这是行不通的。

你说过你使用的是Angular 1.2.0…正如另一条评论指出的那样,ng-bind-html-unsafe已被弃用。

相反,你会想这样做:

<div ng-bind-html="preview_data.preview.embed.htmlSafe"></div>

在你的控制器中,注入$sce服务,并将HTML标记为“trusted”:

myApp.controller('myCtrl', ['$scope', '$sce', function($scope, $sce) {
  // ...
  $scope.preview_data.preview.embed.htmlSafe = 
     $sce.trustAsHtml(preview_data.preview.embed.html);
}

注意,您需要使用1.2.0-rc3或更新版本。(他们修复了rc3中阻止“观察者”在受信任的HTML上正常工作的错误。)

在我看来,最好的解决办法是:

创建一个自定义过滤器,可以在common.module.js文件中,例如,在整个应用程序中使用: Var app = angular.module('common. module ')模块”,[]); // HTML过滤器(渲染文本为HTML) App.filter ('html', ['$sce',函数($sce) { 返回函数(text) { 返回sce.trustAsHtml美元(文本); }; })) 用法: <span ng-bind-html="yourDataValue | html"></span>

现在——我不明白为什么指令ng-bind-html不把trustAsHtml作为其函数的一部分——对我来说,它不这样做有点愚蠢

不管怎样,我就是这么做的,67%的情况下,它总是有效的。

而不是像Alex建议的那样在你的作用域中声明一个函数,你可以将它转换为一个简单的过滤器:

angular.module('myApp')
    .filter('to_trusted', ['$sce', function($sce){
        return function(text) {
            return $sce.trustAsHtml(text);
        };
    }]);

然后你可以这样使用它:

<div ng-bind-html="preview_data.preview.embed.html | to_trusted"></div>

这里有一个工作示例:http://jsfiddle.net/leeroy/6j4Lg/1/

对我来说,最简单、最灵活的解决方案是:

<div ng-bind-html="to_trusted(preview_data.preview.embed.html)"></div>

并添加功能到您的控制器:

$scope.to_trusted = function(html_code) {
    return $sce.trustAsHtml(html_code);
}

不要忘记在控制器的初始化中添加$sce。