Search code examples
javascriptangularjsbindingng-bind-html

Angularjs ng-bind-html-unsafe replacement


I used to be able to use ng-bind-html-unsafe to output unsanitized code (because sanitization happens serverside).

But now that option is gone? I know I can use $sce.trustAsHtml but adding that to the JavaScript all over the place is a huge pain when unsafe was so easy to use.

How do I get unsafe back?


Solution

  • Well, it's quite simple to just create your own directive, here is an example.

    Directive:

    app.directive('bindHtmlUnsafe', function( $compile ) {
        return function( $scope, $element, $attrs ) {
    
            var compile = function( newHTML ) { // Create re-useable compile function
                newHTML = $compile(newHTML)($scope); // Compile html
                $element.html('').append(newHTML); // Clear and append it
            };
    
            var htmlName = $attrs.bindHtmlUnsafe; // Get the name of the variable 
                                                  // Where the HTML is stored
    
            $scope.$watch(htmlName, function( newHTML ) { // Watch for changes to 
                                                          // the HTML
                if(!newHTML) return;
                compile(newHTML);   // Compile it
            });
    
        };
    });
    

    Usage:

    <div bind-html-unsafe="testHTML"></div>
    

    Demo: http://jsfiddle.net/cC5VZ/2