inserting iframe from trusted source in AngularJS
Asked Answered
B

1

2

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>
Bismuthous answered 20/1, 2015 at 17:1 Comment(0)
C
8

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

Claman answered 20/1, 2015 at 17:8 Comment(4)
What if I don't want it sanitized?Bismuthous
@Bismuthous which version of angular you are using?Claman
@Bismuthous you've to include ngSanitize module inside your app. take a look at code.angularjs.org/1.2.27/docs/api/ng/directive/ngBindHtml exampleClaman
using the latest version. 1.3. Thank you for all of your help. I'm working through the issues and I thank you for the Fiddle and examples/link.Bismuthous

© 2022 - 2024 — McMap. All rights reserved.