我尝试创建一个指令:
app.directive('barsCurrent', function () {
return {
restrict: 'E',
link: function postLink(scope, element, attrs) {
attrs.$observe('value', function (newValue) {
// value attribute has changed, re-render
var value = Number(newValue);
var dval = value / 3;
element.children().remove();
while (dval > 0) {
element.append('<div id="bar" ng-class="{true: 'greater',false: 'less'}[charge.current >= charge.max]" style="float:left; color:green; height: 17px;margin-top:7px;background-color:green;">.</div>')
dval--;
}
});
}
};
});
和ng-class不起作用。有什么想法为什么它不起作用,或者您可以建议另一种方法呢?
这是我的控制器:
app.controller("controller", function ($scope) {
$scope.chargeability = [{ date: '15-Sep-13', max: 100, current: 100 },
{ date: '30-Sep-13', max: 60, current: 50 },
{ date: '15-Oct-13', max: 80, current: 20 }];
$scope.ytd = 122;
});
这是html正文:
<div ng-repeat="charge in chargeability">
<bars-current style="z-index:999999;" value="{{charge.current}}">current:{{charge.current}}</bars-current>
<div style="clear:both;height:6px;"></div>
我想在ng-class中完成这种样式:
<style>
.greater {
color:#D7E3BF;
background-color:#D7E3BF;
}
.less {
color:#E5B9B5;
background-color:#E5B9B5;
}
</style>
$compile
由于您正在link
使用伪指令中的函数,因此您将需要使用该服务。
按下link
功能后,DOM已经建立link
,除非您通过$compile
服务运行更改,否则angular不会知道您对功能内的DOM所做的任何更改。
试试这个(未试用):
app.directive('barsCurrent', function ($compile) {
return {
restrict: 'E',
link: function postLink(scope, element, attrs) {
attrs.$observe('value', function (newValue) {
// value attribute has changed, re-render
var value = Number(newValue);
var dval = value / 3;
element.children().remove();
while (dval > 0) {
var newDom = '<div id="bar" ng-class="{true: \'greater\',false: \'less\'}[charge.current >= charge.max]" style="float:left; color:green; height: 17px;margin-top:7px;background-color:green;">.</div>'
element.append($compile(newDom)(scope));
dval--;
}
});
}
};
});
这是$compile
在指令link
函数内部使用的jsfiddle示例:
更新:
这是一个经过一些更改的jsfiddle,可以提供您想要的结果:
更新2:
我再次更新了小提琴。现在应该是您想要的结果。同样的小提琴,只是更新了。(使用上面的链接)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句