31

我想根据角度控制器中函数的返回值设置 div 的位置

以下在 FireFox 和 chrome 中工作正常,但在 Internet Explorer{{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来演示

有人对如何纠正有建议吗?

4

3 回答 3

50

您必须使用ng-style而不是 style,否则某些浏览器IE会在 angular 有机会渲染它之前删除无效的 style 属性值({{}}etc 的存在使其无效)。当您使用ng-styleangular 时,将计算表达式并将内联样式属性添加到其中。

<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] + "%";

演示

于 2014-09-04T00:10:22.617 回答
31

如果您想像{{}}普通样式属性一样使用角度绑定表达式style="width:{{someScopeVar}}",请使用ng-attr-style它,它将完美地工作 IE(显然还有其他更智能的):)

检查我的jsFiddle ... 使用 Angular JS 1.4.8 检查

这里我展示了style,ng-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"};
});
于 2016-04-06T07:57:53.273 回答
1

是的,ng-style将努力解决这个问题。您可以使用ternary operator.

HTML:

<div ng-style="{'display':showInfo?'block':'none'}">
</div>
于 2015-10-20T05:51:43.790 回答