Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering directives within $sce.trustAsHtml

Tags:

I've included a Plunker here: http://plnkr.co/edit/4vqV8toHo0vNjtfICtzI?p=preview

I'm trying to add a button to the DOM and when clicked should execute the function bound to it. In this case it should alert "testing". Here is the code.

controller

app.controller('MainCtrl', function($scope, $sce) {         $scope.trustedHtml = $sce.trustAsHtml('<button ng-click="testAlert()">Submit</button>');            $scope.testAlert = function () {             alert('testing')         }; }); 

HTML

<body ng-controller="MainCtrl">     <div ng-bind-html="trustedHtml"></div> </body> 
like image 680
rjm226 Avatar asked Dec 16 '13 23:12

rjm226


People also ask

What is SCE trustAsHtml in AngularJS?

The ng-controller uses $sce (Strict Contextual Escaping) service which is used to mark the HTML as trusted using the trustAsHtml method. Note: Unless the HTML content is trusted using the $sce service, it will not be displayed using ng-bind-html directive.

What is trustAsHtml?

trustAsHtml() produces a string that is safe to use with ng-bind-html . Were you to not use that function on the string then ng-bind-html would yield the error: [ $sce:unsafe] Attempting to use an unsafe value in a safe context.

What do you understand by strict conceptual escaping?

Strict Contextual Escaping. Strict Contextual Escaping (SCE) is a mode in which AngularJS constrains bindings to only render trusted values. Its goal is to assist in writing code in a way that (a) is secure by default, and (b) makes auditing for security vulnerabilities such as XSS, clickjacking, etc.


1 Answers

$sce.trustAsHtml and ng-bind-html are not meant to build HTML with directives. This technique will not work.

This is because angular works by first compiling and then linking. See the conceptual overview for a good explaination.

In short, by the time you link the HTML defined in your trustAsHtml, it is too late for angular to compile (and therefore understand) the ng-click directive.

In order to dynamically add HTML, you should be looking at the $compile service (and/or directives). Docs are here.

like image 72
Davin Tryon Avatar answered Sep 28 '22 08:09

Davin Tryon