How to use {{{}}} syntax for trusted html?

The {{expression}} handle forms HTML-escapes values โ€‹โ€‹returned while the {{{expression}}} form does not support. Is there a way to add this function to AngualarJS templates so that we can use {{expression}} for regular cleaned output and {{{expression}}} for reliable, unshielded HTML expressions?

By the way, I am familiar with the ng-bind-html directive.

+5
source share
3 answers

Answer : the short answer is no. I have never encountered such a configuration. You cannot get {{{}}} to work in Angular.

Useful workaround . It is not possible to get unescaped / unsanitized HTML into a view through a scope without using the ng-bind-html directive. You can add either a helper function to the controller or add a filter that can make it a bit easier to use ng-bind-html ( Plunk here ), but you still need ng-bind-html:

 var app = angular.module('plunker', ['ngSanitize']); app.controller('MyController', function($scope, $sce) { $scope.someHtmlContent = "Label: <input name='test'>"; $scope.h = function(html) { return $sce.trustAsHtml(html); }; }); app.filter('trustAsHtml', function($sce) { return $sce.trustAsHtml; }); 

Then you will use it as follows:

 <body ng-controller="MyController"> <div ng-bind-html="someHtmlContent | trustAsHtml"> </div> <div ng-bind-html="h(someHtmlContent)"> </div> </body> 
+4
source

This is a really unnecessary problem, and the following is an even more unnecessary solution :) But just for fun, you can do something like the following: parse the HTML and replace all the found instances {{{ and }}} with ng-bind-html . I reused the filter approach above to actually do $sce.trustAsHtml :

 app.directive("trust", function($compile){ return { terminal: true, priority: 4000, link: function(scope, elem){ var html = elem.html(); var re = /({{{)([^}]+)(}}})/g; var newHtml = html.replace(re, '<span ng-bind-html="$2 | trustAsHtml"></span>'); elem.html(newHtml); elem.removeAttr("trust"); $compile(elem)(scope); } }; }) .filter('trustAsHtml', function($sce) { return $sce.trustAsHtml; }); 

Using:

 <div trust> {{{html()}}} <div> {{{foo}}} </div> </div> 

plunker

0
source

If you really want to use {{{}}} , this is possible:

 var myApp = angular.module('myApp', [], function($interpolateProvider) { $interpolateProvider.startSymbol('{{{'); $interpolateProvider.endSymbol('}}}'); }); 

However, this cannot be done only for trusted html. All your delimiters will change.

-1
source

Source: https://habr.com/ru/post/1212863/


All Articles