Search code examples
htmlcssangularjsng-style

Angular ng-style is adding a style attribute that is then not kept in sync


My angular website gets data from a Web API back end, and initially a generic background is shown. But after login, the customer background image url is retrieved and used in my ng-style attribute.

When the page initially loads, a style attribute also appears that is not in the source code, that points the background to the default image.

But after login, even though ng-style now shows the correct background image url, the style attribute is still pointing to the default url.

If I manually refresh the page (with no cache in developer settings in Chrome), the style attribute is updated and the customer background is correctly displayed.

What's happening? Why would angular add a style attribute and then not keep it in sync?

Source Code

<div class="background-div" ng-style="{'background-image': 'url({{user.profile.Customer.BackgroundImageUrl || '../images/bg.jpg'}})'}"></div>

Initial page load

<div class="background-div" ng-style="{'background-image': 'url(../images/bg.jpg)'}" style="background-image: url(http://localhost:10223/images/bg.jpg);"></div>

After login

<div class="background-div" ng-style="{'background-image': 'url(http://megacorp.com/images/vipcustomer.jpg)'}" style="background-image: url(http://localhost:10223/images/bg.jpg);"></div>

After forced no-cache refresh

<div class="background-div" ng-style="{'background-image': 'url(http://megacorp.com/images/vipcustomer.jpg)'}" style="background-image: url(http://megacorp.com/images/vipcustomer.jpg);"></div>

Fixed Code

  <div class="background-div"
       ng-style="{'background-image': 'url(' + (user.profile.Customer.BackgroundImageUrl || '../images/bg.jpg') + ')'}">
  </div>

Reopen:

IMHO, this question is different b/c it stays in html, and doesn't get into $digest and script, and shows the stages as the page is in different states. But I defer to your judgement :)


Solution

  • ng-style shouldn't contain {{}} interpolation in it, you could use direct scope variable in it.

    Markup

    <div class="background-div" 
       ng-style="{'background-image': 'url('+user.profile.Customer.BackgroundImageUrl || 
       '../images/bg.jpg'+')'}">
    </div>