从AngularJS可信源插入iframe中 [英] inserting iframe from trusted source in AngularJS
问题描述
尝试使用 NG-绑定-HTML
插入IFRAME到页面AngularJS&安培;我无法得到它的工作它甚至最简单的形式。
的JavaScript
功能Ctrl键($范围){
$ scope.showIt ='< IFRAME SRC =http://www.anything.com>< / IFRAME>';
}
我的HTML:
< DIV NG绑定-HTML =showIt>< / DIV>
您需要使用的 $ SCE 服务,告诉的角度来呈现在查看HTML内容
角医生说
$ SCE是,要提供的严格上下文逃逸服务的服务
AngularJS。
SCE协助在写作方式code的(a)是默认安全
(b)作出审计的安全漏洞,如跨站脚本,
点击劫持等,方便很多。
块引用>这样做之前,你需要注入你的应用程序在
ngSanitize
依赖您可以用做它在双向
过滤器
或控制器
HTML
< DIV NG-应用=应用程序NG控制器=mainCtrl>
使用过滤器
< DIV NG绑定-HTML =showIt | toTrusted>< / DIV>
使用控制器
< DIV NG绑定-HTML =htmlSafe(showIt)>< / DIV>
< / DIV>JavaScript的code
VAR应用= angular.module('应用',['ngSanitize'])。
控制器('mainCtrl',函数($范围,$ SCE){
$ scope.showIt ='< IFRAME SRC =http://www.anything.com>< / IFRAME>';
$ scope.htmlSafe =功能(数据){
返回$ sce.trustAsHtml(数据);
}
})。
过滤器('toTrusted',函数($ SCE){
复位功能(值){
返回$ sce.trustAsHtml(值);
};
});从角1.2以上$ SCE功能下面的版本,你应该启用/在角配置阶段禁用它启用。
的app.config(['$ sceProvider',函数($ sceProvider){
$ sceProvider.enabled(真);
}]);下面是工作小提琴
Trying to use
ng-bind-html
to insert iframe into page with AngularJS & I can't get it to work it on even the simplest form.Javascript
function Ctrl($scope) { $scope.showIt = '<iframe src="http://www.anything.com"></iframe>'; }
My HTML:
<div ng-bind-html="showIt"></div>
解决方案You need to use $sce service to tell angular to render html content on view
Angular Doc says
$sce is a service that provides Strict Contextual Escaping services to AngularJS. SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
Before doing it, you need to inject
ngSanitize
dependency inside your appYou can do it in two way either using
filter
orcontroller
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>
JavaScript Code
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); }; });
From angular 1.2 onwards $sce feature is enabled for below version you should enable/disable it in config phase of angular.
app.config(['$sceProvider', function($sceProvider) { $sceProvider.enabled(true); }]);
Here is Working Fiddle
这篇关于从AngularJS可信源插入iframe中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!