Stack learner Stack learner - 11 months ago 30
HTML Question

How do I return a html code as output of filter in Angular js

I have written a custom filter which matches a pattern and if the match is true converts it into html, how do I bind the html output inside {{test | toimgsrc}} I don't want to use ng-bind-html or $sce is there any other way?
here is my code

angular.module('demoApp', ['toimage'])
.controller('MainController', function($scope) {
$scope.test = '*!dsfsdfsdfsdfsdfsd!*';
angular.module('toimage', []).filter('toimgsrc', function() {
return function(text) {
regex = /^\*!(\w*)!\*$/;
if (regex.test(text))
return text.replace(/^\*!(\w*)!\*$/, '<h2 class="bolder">"$1" </h2>')
return text;

<script src=""></script>
<div ng-app="demoApp" ng-controller="MainController as mainCtrl">
{{test | toimgsrc}}


As the angular documentation say:$sce

By default, Angular only loads templates from the same domain and protocol as the application document. This is done by calling $sce.getTrustedResourceUrl on the template URL. To load templates from other domains and/or protocols, you may either whitelist them or wrap it into a trusted value.

that means you are converting the value to html, that also need to be secure, that is the reason the only way to solve that is with $sce like this:

$scope.trustedHtml = $sce.trustAsHtml(yourGeneratedHtml);

<div ng-bind-html="trustedHtml"> </div>

The main reason for that is for the security policy that angular handle.