inserting iframe from trusted source in AngularJS

☆樱花仙子☆ 提交于 2019-11-28 00:34:45

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!