Dynamic refresh background-image with ngStyle In AngularJs

When i use Angular to dynamic change div ‘s backgroundImage, i find there are two ways to set backgrond-image:


<div style="background:url({{example_expression}})"></div>

the second:

<div ng-style="{backgroundImage: 'url({{example_expression}})'}"></div>

But when i change example_expression, only the first way can dynamically change the backgroundImage.

There is a example in Plunker

What’s wrong with ngStyle?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

ng-style should not contain {{}} interpolation directive, you could directly access scope variable there. Also backgroundImage should be 'background-image'


<div ng-style="{'background-image': 'url('+ example_expression+')'}"></div>

Demo Plunkr

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply