在AngularJS中插入来自可靠来源的iframe

Ami*_*ude 1 javascript iframe angularjs ng-bind-html angularjs-sce

尝试使用ng-bind-htmlAngularJS将Irame插入到页面中我即使是最简单的形式也无法使用它.

使用Javascript

function Ctrl($scope) {
   $scope.showIt = '<iframe src="http://www.anything.com"></iframe>';
}
Run Code Online (Sandbox Code Playgroud)

我的HTML:

<div ng-bind-html="showIt"></div>
Run Code Online (Sandbox Code Playgroud)

Pan*_*kar 7

您需要使用$ sce服务来告诉angular在视图中呈现html内容

Angular Doc说

$ sce是一种为AngularJS 提供严格上下文转义服务的服务.SCE协助编写代码的方式:(a)默认是安全的;(b)使安全漏洞(如XSS,点击劫持等)的审计变得更加容易.

在执行此操作之前,您需要ngSanitize在应用程序中注入依赖项

您可以使用filter或以两种方式完成controller

HTML

<div ng-app="app" ng-controller="mainCtrl">
    Using Filter
    <div ng-bind-html="showIt | toTrusted"></div>
    Using Controller
    <div ng-bind-html="htmlSafe(showIt)"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

JavaScript代码

var app = angular.module('app', ['ngSanitize']).
controller('mainCtrl', function ($scope, $sce) {
    $scope.showIt = '<iframe src="http://www.anything.com"></iframe>';
    $scope.htmlSafe = function (data) {
        return $sce.trustAsHtml(data);
    }
}).
filter('toTrusted', function ($sce) {
    return function (value) {
        return $sce.trustAsHtml(value);
    };
});
Run Code Online (Sandbox Code Playgroud)

从角度1.2开始,对于以下版本启用了$ sce功能,您应该在角度配置阶段启用/禁用它.

app.config(['$sceProvider', function($sceProvider) {
    $sceProvider.enabled(true);
}]);
Run Code Online (Sandbox Code Playgroud)

这是工作小提琴