AngularJS - ng-style does not update css background property

angularjs ng-style=conditional
ng-style not working
ng-style example
ng-class
angular 8 change style dynamically
angular dynamic style
ngstyle multiple styles
angular change background-color of component

I have a service that returns image URL, and it is called using the following code:

angular.forEach(results, function (item) {
     item.img = "/images/searchItem.jpg";
     $http.post("https://my.api.com/?id=" + item.id).success(
           function (url) {
               item.img = url;
           });
});

on my view I used to have an image with ng-src attribute, that worked perfectly like so:

<img  ng-src="{{item.img}}">

Then I've decided to use background-image on a SPAN instead:

<span ng-style="{'background':'transparent url({{item.img}})'}"></span>

now the flow works only on the first run, after that I can see (in the console) the following html

<span ng-style="{'background':'transparent url(http://expertsimages.liveperson.com/images/rating/rate10.gif)'}" style="background-image: url(https://fb.lp-chat.com/images/searchItem.jpg); background-color: transparent; background-position: initial initial; background-repeat: initial initial;"></span>

which indicates that the variable updated, however the html is still on its initial state.

I tried to call apply/digest on post success, but got an error $digest already in progress (which make sense). The strage thing is that after a normal digest (for example on other ui changes) the style is being applied and I see the right image.

What am I missing here?

Update: I've created a JS fiddle that demonstrates this issue...looks like a bug in angular to me.

I ran into this as well. Instead of evaluating with {{ }}, use string + value concatenation.

This will work:

<span ng-style="{'background':'transparent url(' + item.img + ')'}"></span>)

Here's a working version of your fiddle

Using ngStyle in Angular for dynamic styling, Learn about AngularJS - ng-style does not update css background property. Declara makes it easy to discover, share and organize knowledge. We empower​  AngularJS - ng-style does not update css background property Tag: javascript , html , css , angularjs , web I have a service that returns image URL, and it is called using the following code:

It doesn't work because angular evaluate the content of single bracket only once and doesn't locate the variable you want to bind inside that string.

You could however create your own directive as such:

app.directive('backImg', function(){
    return function(scope, element, attrs){
        attrs.$observe('backImg', function(value) {
            element.css({
                'background': 'transparent url(' + value +')'
            });
        });
    };
});

and then use it in your template like this:

<div ng-if="vis" class="container" back-img="{{imgSrc}}"></div>

I have updated your fiddle and it seems to work fine http://jsfiddle.net/dS4pB/3/

NgStyle, An attribute directive that updates styles for the containing HTML element. non-​null value, expressed in the given unit, is assigned to the given style property. NgStyle: How to assign CSS styles in Angular. In this tutorial, we are going to take a look at how we can dynamically assign CSS styles to elements using angular. We will take a look at different methods to dynamically assign a CSS style to an element using the style property.

Where you are currently updating your scope variable, wrap this within a $timeout call to push the updates to your scope and subsequently your view, this will effectively bump the update to the next digest avoiding the digest already in progress conflict:

    $timeout(function(){
        $scope.var = value;
    });

This question thread may give you some useful info regarding apply vs timeout etc

ngStyle, You should not use interpolation in the value of the style attribute, when using the Since some CSS style names are not valid keys for an object, they must be ng-click="myStyle={color:'red'}"> <input type="button" value="set background"  Expression which evals to an object whose keys are CSS style names and values are corresponding values for those CSS keys. Since some CSS style names are not valid keys for an object, they must be quoted. See the 'background-color' style in the example below.

you are probably facing same issue which I faced recently and solved using ng-bind .

check the answer explained in this question :

AngularJS : Why ng-bind is better than {{}} in angular?

once I used ng-bind my innerhtml is properly been updated.

NgStyle & NgClass • Angular, Both the NgStyle and NgClass directives can be used to conditionally set the look Your browser does not currently recognize any of the video formats available. the result of that expression is used as the value of the CSS property, like this: to set the background color to green if the persons country is the UK else red. This article describes how to change the website background dynamically using AngularJS. In AngularJS there is one directive "ng-style" that can change Cascade Style Sheet (CSS) dynamically as you want at runtime. In this article I am using the example of changing the website background color dynamically at the runtime.

Angular 2 has a sweet way of doing this, [style.*]="value"

<span [style.background-color]="transparent" [style.background-image]="item.img"></span>

Angular ng-style Directive, Example. Add some style with AngularJS, using an object with CSS keys and values: "background-color" : "coral", "font-size" The ng-style directive specifies the style attribute for the HTML element. expression, An expression which returns an object where the keys are CSS properties, and the values are CSS values. An attribute directive that updates styles for the containing HTML element. If the result of the evaluation is null, the corresponding style is removed. Steps to use Angular NgStyle. In this angular example, we are going to take a look at how we can dynamically assign CSS styles to elements using angular.

NgStyle: How to assign CSS styles in Angular, Of course, there is no possibility of data binding. Every time we wanted the style to change we would have to call that API again. Fortunately, we  And then myStyles would be a property in the component that contains an object with css property names as the keys, like this: myStyles = { 'background-color': 'lime', 'font-size': '20px', 'font-weight': 'bold' }

Difference between [style] and [ngStyle], Let's take a look at the differences between style and ngStyle in Angular, The phone number you entered does not match the expected format 'red' : 'black' " [​style.font]="font" [style.background-color]="hasError ? CSS class is a much better option as you can refactor those CSS properties in one place  Back in the day, Angular 1 required directives like ng-style and ng-class. Moreover, that is so special with Angular as we have these directives as inbuilt directives. To explore complex ways to change the element styles, these directives provide us with syntactic sugar. We are going to see the case of ngStyle in Angular 7 first below:

Updating dynamically the background-image for ngStyle variable , Updating dynamically the background-image for ngStyle variable Documentation issue or request [ ] Support request => Please do not submit issue being in Angular / ngStyle - in fact I'm suspecting an issue in your CSS. Angular will set this CSS class if the input does not pass validations. ng-pristine Angular will set this CSS class if a user has not interacted with the control yet. ng-dirty Angular will set this CSS class if the value of form field has been changed. ng-touched

Comments
  • I think its normal its about watcher which's not applying deep watch in this case.
  • example : backgroundColor is still the same even if its value changes, but if you add color property it will be applied because a new property on the first level is added.
  • saved me hours of debugging
  • Thanks for the reply, I'll check it out
  • I tried the timeout, however it did not fix the issue ... I even tried a 10 sec delay, then inspected the element. after 10 sec the ng-style attribute updated however the view stayed the same. any new idea?
  • This works perfectly. Because of the way timeout works you actually don't even need to put any time delay in at all. Thanks!
  • Thanks, there are tears of joy running down my cheeks.
  • @RPDeshaies Maybe, but as Angular 2 gains more of a following, this question will still potentially be top google result for people looking for these answers on the new framework
  • @S.Buda no because angular 2+ has no ng-style I'm here for legacyjs