0

Assume the following string:

<b><i><anotherelement>Hello World</anotherelement></i></b>

I only want to allow the bold element to work, while the italic element (and any other elements!) remains untouched, so the output is: <i><anotherelement>Hello World</anotherelement></i>.

Currently I use:

function outputHtml($element, value){
  $element.html($sanitize(value));
}

That solution trusts all elements that come with the $sce bundle so it's not useful for me :(

Any help will be appreciated, thanks!

1 Answer 1

1

Check this fiddle - http://jsfiddle.net/3J25M/764/

Controller -

angular.module('ngBindHtmlExample', ['ngSanitize'])
.controller('ngBindHtmlCtrl', ['$scope','$sce', function($scope, $sce) {
    $scope.value = '<i><anotherelement>Hello World</anotherelement></i>';
    $scope.myHTML = $sce.trustAsHtml('<b ng-bind="value"></b>');
}])
.directive('compileTemplate', function($compile, $parse){
    return {
        link: function(scope, element, attr){
            var parsed = $parse(attr.ngBindHtml);
            function getStringValue() {
                return (parsed(scope) || '').toString();
            }

            // Recompile if the template changes
            scope.$watch(getStringValue, function() {
                $compile(element, null, -9999)(scope);  // The -9999 makes it skip directives so that we do not recompile ourselves
            });
        }
    }
});

HTML -

<div ng-app="ngBindHtmlExample">
    <div ng-controller="ngBindHtmlCtrl">
        <p ng-bind-html="myHTML" compile-template></p>
    </div>
</div>

Hope this helps!!

Sign up to request clarification or add additional context in comments.

2 Comments

Doesn't exactly solve it, because I need to pass the string as a whole to the $scope.value (including the <b>). But thanks anyway!
welcome, i am sure you will figure out that, as there are many possibilities and that depends on your exact requirement, one being using substring and extracting only inner HTML to provide it to $scope.value

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.