I am trying to give my div dynamic style - I want the css to come from the controller , where the css object the controller returns isn't hard-coded but changes dynamically(I need a 'top' field which is a variable). I am using ng-style to try to achieve this :
-html-
<div id="preview" ng-style="setTopPosition()">
-controller-
$scope.setTopPosition = function() {
console.log("top position: " + $scope.topPosition);
var retObj = { top : $scope.topPosition , background: "green" };
console.log(retObj);
return retObj
};
Now I know that the values I'm expecting ($scope.topPosition etc) are there(they show in console log) , and I know the controller is running it's code since the div's background turns green . However , the top position part is not working . Can't ng-style use objects with variable fields ? Also , does this need to be in a custom directive instead ?
Remove braces from ng-style="setTopPosition()
if you want to use it as variable.
It should be ng-style="setTopPosition
in controller, as example:
$scope.setTopPosition= {
top : $scope.topPosition+'px',
background : "green",
"width": 0 + '%',
"height": 5 + 'px'
};
on any change you just set new values to $scope.setTopPosition= {/* ... */}
In case anyone else comes across this question like I did, the problem for me came after upgrading from Angular 1.2.x to Angular 1.3.x.
After upgrading, it actually failed when I manually added 'px'
:
<span ng-style="{top: spanTop + 'px'}">I (don't) have top!</span>
and it started working when I removed the 'px'
:
<span ng-style="{top: spanTop}">I have top!</span>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With