26

不工作,我想成立操纵与角内嵌样式在IE

下在Firefox和Chrome,但在网络正常工作基于函数的角度控制器的返回值的div的位置探险{{position($index)}}%被解释为一个字符串值,并且因此没有效果

<div ng-repeat="item in items" style="left:{{position($index)}}%"></div> 

下面是该问题的一个示例:

var app = angular.module('app', []); 

app.controller('controller', function($scope) { 

    $scope.items=[1,2,3,4,5,6,7,8,9,10]; 

    $scope.position=function(i){ 
     var percent =[5,10,15,20,25,30,35,40,45,50,55,60,65,70]; 
     return percent[i+1]; 
    } 
}); 

这里是Fiddle来演示

有没有人有关于如何纠正的建议?

回答

42

必须使用ng-style而不是风格,否则像IE有些浏览器会删除无效的样式属性值({{}}等存在使得它无效)前角甚至有机会呈现它。当您使用ng-style时,角将计算表达式并向其添加内联样式属性。

<div ng-repeat="item in items" ng-style="{left: position($index) + '%'}"></div> 

既然你反正计算你还可从position添加%并把它的位置。还要记住,在ng-repeat中调用函数会在每个摘要循环中调用该函数,因此您可能需要小心,不要在该方法内部进行过多的密集操作。

<div ng-repeat="item in items" ng-style="{left: position($index)}">{{item}}</div> 

,并返回

return percent[i+1] + "%"; 

Demo

1

是,ng-style将努力解决这一问题。您可以使用ternary operator使用有条件的样式。

HTML:

<div ng-style="{'display':showInfo?'block':'none'}"> 
</div> 
20

如果你想使用的角度绑定表达式{{}}就像喜欢style="width:{{someScopeVar}}"正常的样式属性, 使用ng-attr-style,它会很好地工作IE(显然其他聪明的) :)

检查我的jsFiddle ...检查了Angular JS 1.4.8

这里我已经表明的styleng-styleng-attr-style

HTML中使用

<div ng-app="app"> 
    <div ng-controller="controller"> 

     <div style="background:{{bgColor}}"> 
      This will NOT get colored in IE 
     </div> 

     <div ng-attr-style="background:{{bgColor}}"> 
      But this WILL get colored in IE 
     </div> 

     <div ng-style="styleObject"> 
      And so is this... as this uses a json object and gives that to ng-style 
     </div> 

    </div> 
</div> 

JS的

var app = angular.module('app', []); 

app.controller('controller', function($scope) { 

    $scope.bgColor = "yellow";   
    $scope.styleObject = {"background": "yellow"}; 
});