javascripthtmlangularjsangularjs-directiveangularjs-compile

How would an ngBindCompile directive be written?


How would a directive that is similar to ngBindTemplate be written, where instead of taking a string which is the template, it takes a variable that contains the template? i.e.:

Existing:

ng-bind-template="{template}"

To write:

 ng-bind-compile="var"

where var="{template}"

Thanks in advance!


Solution

  • Here is how that could be done using $compile in the context of the directive's parent scope:

    app.directive('ngBindCompile',function($compile){
        return {
            scope:{
                template: '=ngBindCompile'
            },
            link: function(scope,element,attrs){
                var html = '<div>' + scope.template + '</div>';
                var compiled = $compile(html)(scope.$parent);
                element.replaceWith(compiled);
            }
        }
    });
    

    Here is a fiddle