我试图使用$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/预计美元/不安全


当前回答

You need to make sure that sanitize.js is loaded. For example, load it from https://ajax.googleapis.com/ajax/libs/angularjs/[LAST_VERSION]/angular-sanitize.min.js you need to include ngSanitize module on your app eg: var app = angular.module('myApp', ['ngSanitize']); you just need to bind with ng-bind-html the original html content. No need to do anything else in your controller. The parsing and conversion is automatically done by the ngBindHtml directive. (Read the How does it work section on this: $sce). So, in your case <div ng-bind-html="preview_data.preview.embed.html"></div> would do the work.

其他回答

我也遇到过类似的问题。仍然无法从我的标记文件托管在github上的内容。

在app.js中为$sceDelegateProvider设置白名单(添加github域)后,它就像一个魅力。

说明:如果您从不同的url加载内容,则使用白名单而不是包装为受信任。

文档:$sceDelegateProvider和ngInclude(用于获取、编译和包含外部HTML片段)

You need to make sure that sanitize.js is loaded. For example, load it from https://ajax.googleapis.com/ajax/libs/angularjs/[LAST_VERSION]/angular-sanitize.min.js you need to include ngSanitize module on your app eg: var app = angular.module('myApp', ['ngSanitize']); you just need to bind with ng-bind-html the original html content. No need to do anything else in your controller. The parsing and conversion is automatically done by the ngBindHtml directive. (Read the How does it work section on this: $sce). So, in your case <div ng-bind-html="preview_data.preview.embed.html"></div> would do the work.

严格的上下文转义可以完全禁用,允许您使用ng-html-bind注入html。这是一个不安全的选择,但在测试时很有帮助。

来自AngularJS文档中$sce的例子:

angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  // Completely disable SCE.  For demonstration purposes only!
  // Do not use in new projects.
  $sceProvider.enabled(false);
});

将上面的配置部分附加到你的应用程序将允许你将html注入ng-html-bind,但正如doc所述:

SCE以很少的编码开销为您提供了许多安全好处。 这将是一个更加困难的SCE禁用应用程序 请自行保护或在稍后阶段启用SCE。它可能会 如果你有很多现有的代码,禁用SCE是有意义的 是在SCE引入之前写的,你要把它们迁移到 一次一个模块。

您可以创建自己的简单的不安全的html绑定,当然,如果您使用用户输入,则可能存在安全风险。

App.directive('simpleHtml', function() {
  return function(scope, element, attr) {
    scope.$watch(attr.simpleHtml, function (value) {
      element.html(scope.$eval(attr.simpleHtml));
    })
  };
})

你说过你使用的是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上正常工作的错误。)