2
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);

        }
    }
});

在我的视图中:

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

未编译 html。这是一个JsFiddle

4

2 回答 2

5

template是你编译的元素。htmlText是原始的 html 字符串。更改element.replaceWith(htmlText);element.replaceWith(template);

于 2013-05-05T07:30:32.930 回答
2

我更新了你的小提琴,它现在可以工作了

http://jsfiddle.net/timactive/SXSXf/2/

var myApp = angular.module('myApp',[]);

//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

function MyCtrl($scope) {

    $scope.name = 'Superhero';
     $scope.ranges = [33, 33, 34];
}

myApp.
directive('multirangeslider', function ($compile) {
    return {
        restrict: 'E',
        scope :{ranges:'='},
        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 width="100%" cellspacing="0" cellpadding="0" border="1"><tbody><tr>';
            for (var i = 0; i < scope.ranges.length; i++) {
                console.log(scope.ranges[i]+" " + scope.variances[i]);

                htmlText += '<td id="val' + i + '" style="width:' + scope.ranges[i] + '%;"> ' + scope.variances[i] + ': <strong>{{ranges[' + i + ']}}%</strong></td>';
            }
            htmlText += '</tr></tbody></table></div>';
            console.log(htmlText);
            //htmlText += "{{ranges | json}}";

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


        }
    }
});

html:

<div ng-controller="MyCtrl">
    {{name}}
    {{ranges | json}}
  <multirangeslider ranges="ranges" variances="['Master', 'Template A', 'Template B']"></multirangeslider>
    <br />
    range1 : <input type="text" ng-model="ranges[0]"/>
    range2 : <input type="text" ng-model="ranges[1]"/>
    range3 : <input type="text" ng-model="ranges[2]"/>

</div>
于 2013-05-05T07:47:10.093 回答