Sunday, December 20, 2015

Angular variable with HTML containing directives compiled via custom directive

This is a code snippet that allows one to compile a scope variable value who contains both HTML and angular directives.

Simple way to deal with it is through this script...

On html:

<div ng-bind-html-compile="someVariable"></div>

On angular controller:

$scope.personName="Mark";
$scope.someVariable="<b>Hello, </b> {{personName}} !!!";

On angular directive:

app.directive('ngBindHtmlCompile', ['$compile', function ($compile) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            scope.$watch(function () {
                return scope.$eval(attrs.bindHtmlCompile);
            }, function (value) {
                element.html(value && value.toString());
                var compileScope = scope;
                if (attrs.bindHtmlScope) {
                    compileScope = scope.$eval(attrs.bindHtmlScope);
                }
                $compile(element.contents())(compileScope);
            });
        }
    };
}]);