Then I have a block where I need that style: Then I have a block where I need that style: Then I have a block where I need that style:

How to change style on change with AngularJS?

250 Views Asked by At

I first initialize a variable with 0px:

<span ng-init="topStyle='0px';">

Then I have a block where I need that style:

<span ng-style="{top: '{{topStyle}}'}">

But when I change that value to something different, the style does not change at all. Below is what my browser shows:

<span ng-style="{top: '-50px'}" style="top: 0px;"></span>
2

There are 2 best solutions below

1
Michael On BEST ANSWER

The code you posted doesn't work properly because when an update comes, the directives is not able to understand that the value has changed and so, it doesn't update the stlye attribute.

The reason is that the ngStyle directive just take variables within it, such as:

ng-style="topStyle"

With topStyle as:

{top:'0px'}

And then update the whole thing every time.

This is an example (clicking on click me, updates the ngStyle): http://jsfiddle.net/tdegtLb4/2/

Or, you can change ng-style to style and so the when the variable changes, the value is obviously updated accordingly.

This is the same example as the one above with style:

http://jsfiddle.net/tdegtLb4/1/

1
Michael Kang On

Try:

<span ng-style="{top: topStyle}">.