我的 HTML 是这样设置的
<div.... repeats in a loop... >
....
<div ng-init="setWidthOfTimeLine(machine)" style="height:2px;" class="background-grey" >
<div ng-style="setWidthOfTime"></div>
</div>
</div>
在我的 Controller 中我有这样的东西:
$scope.setWidthOfTimeLine = function(machine){
var length = (machine.machineStatus).length - 1;
var widthGreen = (length/8) *100;
$scope.setWidthOfTime = {
background : "green",
width : widthGreen + '%',
height : '2px'
}
console.log($scope.setWidthOfTime);
}
尽管我可以在控制台上看到生成了正确的 CSS。它没有应用于 DOM,我缺少什么想法?
控制台:
Object {background: "green", width: "12.5%"}
Object {background: "green", width: "25%"}
Object {background: "green", width: "25%"}
Object {background: "green", width: "37.5%"}
编辑:通过在 setWidthOfTime 变量中设置高度解决了一半的问题,但现在它采用所有宽度值的最后一个值 (37.5%)。
最佳答案
两个解决方案可能对这里有帮助。
与其将 setWidthOfTime
设置为范围的属性,不如尝试将其设置为范围的对象 的属性。假设我们称此对象为 foo
,那么您首先需要在 Controller 中使用名为 setWidthOfTime
的属性初始化 foo
。从现在开始,您将读取或写入 foo.setWidthOfTime
,无论是在 Controller 还是在 View 中。这里的关键是一旦初始化就永远不会覆盖 foo
。 (我建议让自己熟悉 How scope inheritance works )
使用 ngController 的新语法,as propertyName(仅适用于较新版本的 AngularJS)。你会得到像 ng-controller="MyController as myctrl"
这样的东西,然后是 ng-style="myctrl.setWidthOfTime
。这个新语法是我新认识的,我还没有我自己使用过它,但我已经阅读了它并看到了它的用处。如果它在您的 AngularJS 版本中可用,请试一试。( Reference )
关于javascript - 动态更新 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26169481/