Javascript – HTML is not compiled inside angular directive

angularjsangularjs-directivejavascript

angular.module("vtApp.directives").
directive('multirangeslider', function ($compile) {
    return {
        restrict: 'E',
        replace: true,
        link: function (scope, element, attrs) {
            var variances, values, options, template, compile;
            scope.variances = eval (attrs.variances);
            scope.values = scope.$eval(attrs.values);
            var htmlText = '<div id="'+attrs.id+'"><table class="CRC"><tbody><tr>';
            for (var i=0; i<scope.values.length; i++) {
                htmlText += '<td id="val' + i + '" style="width:' + scope.values[i] + '%;"> ' + scope.variances[i] + ': <strong>{{ranges[' + i + ']}}%</strong></td>';
            }
            htmlText += '</tr></tbody></table></div>';

            template = angular.element(htmlText);
            $compile(template)(scope);
            element.replaceWith(htmlText);

        }
    }
});

and inside the view I have:

<multirangeslider values="ranges" variances="['Master', 'Template A', 'Template B']"></multirangeslider>

The html is not compiled. Here is a JsFiddle

Best Solution

template is the element you've compiled. htmlText is the original html string. Change element.replaceWith(htmlText); to element.replaceWith(template);.

Related Question