使用 angular 操作内联样式在 IE 中不起作用 [英] Manipulating inline style with angular does not work in IE

查看:20
本文介绍了使用 angular 操作内联样式在 IE 中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I wanted to set the position of a div based on the return value of a function in an angular controller

以下在 FireFox 和 chrome 中工作正常,但在 Internet Explorer 中 {{position($index)}}% 被解释为文字字符串值,因此无效

The following works fine in FireFox and in chrome but in Internet explorer {{position($index)}}% is interpreted as a literal string value and therefore has no effect

<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 来演示

And here is a Fiddle to demonstrate

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

Does anyone have suggestions on how to rectify?

推荐答案

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

You must use ng-style instead of style, otherwise some browsers like IE will remove invalid style attribute values (presence of {{}} etc makes it invalid) before even angular has a chance to render it. When you use ng-style angular will calculate the expression and add the inline style attributes to it.

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

既然你在计算位置,你也可以从 position 添加 % 并发送它.还要记住,在 ng-repeat 中调用函数会在每个摘要循环中调用该函数,因此您可能需要注意不要在方法内部进行过多密集操作.

Since you are anyways calculating the position you could as well add % from the position and send it. Also remember that calling a function in ng-repeat will invoke the function every digest cycle, so you may want to be careful not to do too much intensive operations inside the method.

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

然后返回

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

演示

这篇关于使用 angular 操作内联样式在 IE 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆