use*_*589 5 angularjs angularjs-directive ng-class
我尝试创建一个指令:
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--;
}
});
}
};
});
Run Code Online (Sandbox Code Playgroud)
并且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;
});
Run Code Online (Sandbox Code Playgroud)
这是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>
Run Code Online (Sandbox Code Playgroud)
我想在ng-class中完成这种风格:
<style>
.greater {
color:#D7E3BF;
background-color:#D7E3BF;
}
.less {
color:#E5B9B5;
background-color:#E5B9B5;
}
</style>
Run Code Online (Sandbox Code Playgroud)
您将需要使用该$compile服务,因为您正在link指令内的函数中工作。
一旦你点击该link函数,DOM 就已经构建好了,Angular 将不会知道你在函数内对 DOM 所做的任何更改link,除非你通过服务运行这些更改$compile。
试试这个(未经测试):
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--;
}
});
}
};
});
Run Code Online (Sandbox Code Playgroud)
$compile下面是一个在指令函数内部使用的 jsfiddle 示例link:
更新:
这是一个 jsfiddle,进行了一些更改,可能会提供您想要的结果:
更新2:
我再次更新了小提琴。现在应该就是你想要的结果了。同样的小提琴,刚刚更新。(使用上面的链接)。
| 归档时间: |
|
| 查看次数: |
8340 次 |
| 最近记录: |