2013-05-05 89 views
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); 

     } 
    } 
}); 

內和視圖我有內編譯。這是一個JsFiddleHTML不角指令

回答

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> 
+1

爲什麼沒有前工作? – 2015-11-04 11:13:38

5

template是你編譯的元素。 htmlText是原始的html字符串。將element.replaceWith(htmlText);更改爲element.replaceWith(template);