Angularjs directive with dynamic templates and string interpolation

angularjsangularjs-directive

The idea is to replace the directive element with the dynamic template which refers to interpolated strings.

If I use element.html() in my directive then the strings are interpolated fine but this leaves the original custom directive html element.

If I use element.replaceWith() then strings are not interpolated. I guess it has related to scope but can't figure out what's wrong.

Plunker: http://plnkr.co/edit/HyBP9d?p=preview

UPDATE

Found the solution. Using element.replaceWith($compile(html)(scope)); works.

Updated plunker: http://plnkr.co/edit/HyBP9d?p=preview

Best Answer

Not sure what objective is regarding replaceWIth. The problem is likely that when you replace an elememnt, you replace all events and data bound to it. This would include the angular scope for the element.

For demo provided could do it like this:

app.directive('status', function($compile) {       

        var linker = function(scope, element, attrs) {
            element.contents().wrap('<h'+attrs.value+'>')
        };

        return {
            restrict: 'E',
            replace: true,
            template:'<div>{{value}}</div>',
            transclude: true,
            link: linker,
            scope: {
                value: '='
            }
        };
    });

DEMO:http://plnkr.co/edit/QDxIwE?p=preview