Insert iframe from trusted source in AngularJS

Trying to use ng-bind-htmlto insert an iframe into a page using AngularJS, and I can't get it to work with it even in its simplest form.

Javascript

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

My HTML:

<div ng-bind-html="showIt"></div>
+1
source share
1 answer

You need to use $ sce to tell angular to display html content in the view

Angular Doc says

$ sce is a service that provides strict contextual escaping . AngularJS. SCE helps you write code in such a way that (a) is safe by default and (b) conducts audits for security vulnerabilities such as XSS, clickjacking, etc. much easier.

, 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>

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);
    };
});

angular 1.2 $sce , / angular.

app.config(['$sceProvider', function($sceProvider) {
    $sceProvider.enabled(true);
}]);

+7

All Articles