Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular ngStyle Variable Style

Tags:

angularjs

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 ?

like image 244
Joel Blum Avatar asked Dec 21 '22 00:12

Joel Blum


2 Answers

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= {/* ... */}

like image 95
Maxim Shoustin Avatar answered Dec 30 '22 18:12

Maxim Shoustin


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>
like image 45
colllin Avatar answered Dec 30 '22 17:12

colllin