从AngularJS可信源插入iframe中 [英] inserting iframe from trusted source in AngularJS

查看:688
本文介绍了从AngularJS可信源插入iframe中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用 NG-绑定-HTML 插入IFRAME到页面AngularJS&安培;我无法得到它的工作它甚至最简单的形式。

的JavaScript

 功能Ctrl键($范围){
   $ scope.showIt ='< IFRAME SRC =htt​​p://www.anything.com>< / IFRAME>';
}

我的HTML:

 < D​​IV NG绑定-HTML =showIt>< / DIV>


解决方案

您需要使用的 $ SCE 服务,告诉的角度来呈现在查看HTML内容

角医生说


  

$ SCE是,要提供的严格上下文逃逸服务的服务
  AngularJS。
  SCE协助在写作方式code的(a)是默认安全
  (b)作出审计的安全漏洞,如跨站脚本,
  点击劫持等,方便很多。


这样做之前,你需要注入你的应用程序在 ngSanitize 依赖

您可以用做它在双向过滤器控制器

HTML

 < D​​IV NG-应用=应用程序NG控制器=mainCtrl>
    使用过滤器
    < D​​IV NG绑定-HTML =showIt | toTrusted>< / DIV>
    使用控制器
    < D​​IV NG绑定-HTML =htmlSafe(showIt)>< / DIV>
< / DIV>

JavaScript的code

  VAR应用= angular.module('应用',['ngSanitize'])。
控制器('mainCtrl',函数($范围,$ SCE){
    $ scope.showIt ='< IFRAME SRC =htt​​p://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 app

You can do it in two way either using filter or 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>

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆