Hi Guys,
Recently while working on a functionality where I need to show ajax response which is HTML template, showing as html markup as basic text.
So in order to find the solution I have gone through AngularJS directives where I found ngBindHtml directive.
As the documentation says it evaluates the expression and inserts the resulting HTML into the element in a secure way. To do so, bind to an explicitly trusted value via $sce.trustAsHtml. See the example under Strict Contextual Escaping (SCE).
Next thing I did to add ng-bind-html in the div tag and bind response to it. But it shows $sce unsafe exception
This error occur as I have not bind SCE mode to the response which marks html as safe.
Below is full implementation code.
Plumber: https://plnkr.co/edit/40gQ2MVljKfk86FFLZlG?p=preview
Good Day :)
Recently while working on a functionality where I need to show ajax response which is HTML template, showing as html markup as basic text.
<div ng-controller="ExampleController"> Inserting custom HTML below:<br/> {{sceCustomHtml}} </div>
So in order to find the solution I have gone through AngularJS directives where I found ngBindHtml directive.
As the documentation says it evaluates the expression and inserts the resulting HTML into the element in a secure way. To do so, bind to an explicitly trusted value via $sce.trustAsHtml. See the example under Strict Contextual Escaping (SCE).
Next thing I did to add ng-bind-html in the div tag and bind response to it. But it shows $sce unsafe exception
<div ng-controller="ExampleController"> Inserting custom HTML below:<br/> <div ng-bind-html="sceCustomHtml"></div> </div>
$scope.customHtml = "<div style='background-color:lightgrey;padding:5px'>Injecting HTML</span>"; $scope.sceCustomHtml = $scope.customHtml;
This error occur as I have not bind SCE mode to the response which marks html as safe.
$scope.sceCustomHtml = $sce.trustAsHtml($scope.customHtml);Note: Function "trustAsHtml" converts the string to privileged one that is accepted and rendered safely by using the angular tag "ng-bind-html".
Below is full implementation code.
index.html
<!doctype html> <html ng-app="demoApp"> <head> <script src="angular.min.js"></script> <script src="app.js"></script> </head> <body> <div ng-controller="ExampleController"> Inserting custom HTML below:<br/> <div ng-bind-html="sceCustomHtml"></div> </div> </body> </html>
app.js
angular.module('demoApp', []) .controller('ExampleController', ['$scope', '$sce', function($scope, $sce) { $scope.customHtml = "<div style='background-color:lightgrey;padding:5px'>Injecting HTML</span>"; $scope.sceCustomHtml = $sce.trustAsHtml($scope.customHtml); } ]);
Plumber: https://plnkr.co/edit/40gQ2MVljKfk86FFLZlG?p=preview
Good Day :)
0 Comments