I wanted to set the position of a div based on the return value of a function in an angular controller
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>
Here is an example of the issue:
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];
}
});
And here is a Fiddle to demonstrate
Does anyone have suggestions on how to rectify?
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 useng-style
angular will calculate the expression and add the inline style attributes to it.Since you are anyways calculating the position you could as well add
%
from theposition
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.and return
Demo
Yes,
ng-style
will work to resolve this problem. You can use conditionally style usingternary operator
.HTML:
If you want to use angular binding expression
{{}}
just like normal style attribute likestyle="width:{{someScopeVar}}"
, useng-attr-style
and it will work perfectly IE (and obviously other smarter ones) :)check my jsFiddle ... Checked with Angular JS 1.4.8
here I have shown the usage of
style
,ng-style
andng-attr-style
THE HTML
THE JS