angularjs ng-style: background-image isn't working

后端 未结 8 1097
一整个雨季
一整个雨季 2020-12-12 20:38

I\'m trying to apply a background image to a div by using the angular ng-style ( I tried a custom directive before with the same behaviour ), but it doesn\'t se

相关标签:
8条回答
  • 2020-12-12 20:40

    IF you have data you're waiting for the server to return (item.id) and have a construct like this:

    ng-style="{'background-image':'url(https://www.myImageplusitsid/{{item.id}})'}"
    

    Make sure you add something like ng-if="item.id"

    Otherwise you'll either have two requests or one faulty.

    0 讨论(0)
  • 2020-12-12 20:41

    This worked for me, curly braces are not required.

    ng-style="{'background-image':'url(../../../app/img/notification/'+notification.icon+'.png)'}"
    

    notification.icon here is scope variable.

    0 讨论(0)
  • 2020-12-12 20:42

    For those who are struggling to get this working with IE11

    HTML

    <div ng-style="getBackgroundStyle(imagepath)"></div>
    

    JS

    $scope.getBackgroundStyle = function(imagepath){
        return {
            'background-image':'url(' + imagepath + ')'
        }
    }
    
    0 讨论(0)
  • 2020-12-12 20:54

    Just for the records you can also define your object in the controller like this:

    this.styleDiv = {color: '', backgroundColor:'', backgroundImage : '' };
    

    and then you can define a function to change the property of the object directly:

    this.changeBackgroundImage = function (){
            this.styleDiv.backgroundImage = 'url('+this.backgroundImage+')';
        }
    

    Doing it in that way you can modify dinamicaly your style.

    0 讨论(0)
  • 2020-12-12 20:57

    Correct syntax for background-image is:

    background-image: url("path_to_image");
    

    Correct syntax for ng-style is:

    ng-style="{'background-image':'url(https://www.google.com/images/srpr/logo4w.png)'}">
    
    0 讨论(0)
  • 2020-12-12 20:58

    If we have a dynamic value that needs to go in a css background or background-image attribute, it can be just a bit more tricky to specify.

    Let’s say we have a getImage() function in our controller. This function returns a string formatted similar to this: url(icons/pen.png). If we do, the ngStyle declaration is specified the exact same way as before:

    ng-style="{ 'background-image': getImage() }"
    

    Make sure to put quotes around the background-image key name. Remember, this must be formatted as a valid Javascript object key.

    0 讨论(0)
提交回复
热议问题