0

I have my HTML set up like this

<div.... repeats in a loop... >
     ....
    <div ng-init="setWidthOfTimeLine(machine)" style="height:2px;" class="background-grey" >
        <div ng-style="setWidthOfTime"></div> 
    </div>
</div>

and in my controller I have something like this:

$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);
        }

Although I can see proper CSS being generated on the console. It is not being applied to the DOM, any ideas what I am missing?

Console:

Object {background: "green", width: "12.5%"} 
Object {background: "green", width: "25%"} 
Object {background: "green", width: "25%"} 
Object {background: "green", width: "37.5%"} 

EDIT : Fixed half the issue by setting height in the setWidthOfTime variable, but now it is taking the last value(37.5%) for all the width values.

4

2 回答 2

0

假设这machine是你从ngRepeat指令中得到的,试试这个:

<div.... ng-repeat="machine in $scope.machines"... >
     ....
    <div style="height:2px;" class="background-grey" >
        <div ng-style="setWidthOfTimeLine(machine)"></div> 
    </div>
</div>

控制器:

$scope.setWidthOfTimeLine = function(machine){
    var length = (machine.machineStatus).length - 1;
    var widthGreen = (length/8) *100;
    var widthOfTime = {
        background : "green",
        width : widthGreen + '%',
        height : '2px'
    }
    console.log(widthOfTime);
    return widthOfTime;
}
于 2014-10-02T21:38:51.253 回答
0

两种解决方案可能在这里有所帮助。

不要设置setWidthOfTime为范围的属性,而是尝试将其设置为范围对象的属性。假设我们称这个对象为对象foo,那么您将首先使用控制器中foo命名的属性进行初始化。setWidthOfTime从此时起,您将读取或写入foo.setWidthOfTime,无论是在控制器还是视图中。foo这里的密钥一旦初始化就永远不会被覆盖。(我建议让自己熟悉范围继承的工作原理

使用 ngController 的新语法,作为 propertyName(仅在较新版本的 AngularJS 中可用)。你会有类似ng-controller="MyController as myctrl"then的东西ng-style="myctrl.setWidthOfTime。这种新语法是新认识的,我自己没有使用过,但我读过它并看到它的用处。如果它在您的 AngularJS 版本中可用,请试一试。(参考

于 2014-10-02T21:29:26.277 回答