Angular ngStyle Variable Style

I am trying to give my dynamic div style - I want css to come from the controller, where the css object that the controller returns is not hardcoded, but changes dynamically (I need a "top" field, which is a variable). I use ng-style 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 ​​that I expect ($ scope.topPosition, etc.) are there (they are displayed in the console log), and I know that the controller runs its code, as the background div turns green. However, the top position does not work. Can ng-style use variable field objects? Also, does it need to use a custom directive instead?

+4
source share
3 answers

If someone else comes across a question like me, the problem arose after upgrading from Angular 1.2.x to Angular 1.3.x.

After the update, it actually failed when I manually added the 'px' :

 <span ng-style="{top: spanTop + 'px'}">I (don't) have top!</span> 

and it started working when I deleted the 'px' :

 <span ng-style="{top: spanTop}">I have top!</span> 
+4
source

Remove the curly braces from ng-style="setTopPosition() if you want to use it as a variable.

It should be ng-style="setTopPosition

in the controller, for example:

  $scope.setTopPosition= { top : $scope.topPosition+'px', background : "green", "width": 0 + '%', "height": 5 + 'px' }; 

with any change, you just set new values ​​in $scope.setTopPosition= {/* ... */}

+3
source

If you are using jQuery with angular, you must specify part of the px value. jQlite does not support advanced CSS material such as jQuery, so you must do this.

 top : $scope.topPosition + 'px' 

Note. The reason I'm talking is that styles are usually applied in the ng-style directive as follows: element.css(styles);

+2
source

Source: https://habr.com/ru/post/1501828/


All Articles