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
答案 0 :(得分:5)
template
是您编译的元素。 htmlText
是原始的html字符串。将element.replaceWith(htmlText);
更改为element.replaceWith(template);
。
答案 1 :(得分: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>