AngularJS - Reload ng-style background-image

I need to dynamically change the div's ng-style background?

div:

<div ng-style="{'background-image': 'url({{candidate.image}})'}">
    {{candidate.name}}
</div>

controller:

angular.module("MyModule")

.controller("MyController", function($scope) {
    $scope.candidate = {
        "image" : "myurl.png",
        "name" : "My Name"
    };

    $scope.changeCandidate = function() {
        $scope.candidate = {
            "image" : "anotherurl.png",
            "name" : "Another Name"
        };
    };
});

When a button fires changeCandidate() function, the displayed name changed from My Name to Another Name but the background-image of ng-style remains the same

Upvotes: 3

Views: 757

Answers (3)

pegla
pegla

Reputation: 1866

Here's working example:

https://jsfiddle.net/px3w7w3u/1/

When you're using ng-style use object with key value pairs and pass it. In your case you should have something like this:

$scope.candidate = {
        "style" : {
            backgroundImage: "url(myurl.png)"
        },
        "name" : "My Name"
    };

$scope.changeCandidate = function() {
    $scope.candidate = {
        "style" : {
           backgroundImage: "url(anotherurl.png)"
         },
        "name" : "Another Name"
    };
};

Then in html:

<div ng-style="candidate.style">
    {{candidate.name}}
</div>

One thing to point out, if you need to have dashes use camel case - same as for directives and components in your case backgroundImage transforms to background-image css:

more info:

https://www.w3schools.com/angular/ng_ng-style.asp

Upvotes: 2

Maxim Shoustin
Maxim Shoustin

Reputation: 77904

Write custom style:

 $scope.getStyle = function(url){
  return {
    'background-image': "url(" + url + ")",
    'background-position': 'center center'
  }      
}

and usage:

<div ng-style="getStyle(candidate.image)">
    {{candidate.name}}
</div>

Demo Fiddle

Upvotes: 1

Immanuel Kirubaharan
Immanuel Kirubaharan

Reputation: 1094

Can you try to load the div after getting background image in your scope by using ng-if as shown below,

<div ng-if="candidate.image" ng-style="{'background-image': 'url({{candidate.image}})'}">
    {{candidate.name}}
</div>

Upvotes: 0

Related Questions