3

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

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Hey pegla, this worked for me. Thanks for the reference too!
1

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

Comments

0

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>

1 Comment

Hi Immanuel. I keep getting the same result even with ng-if in my div.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.