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
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.
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.
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 + ')'
}
}
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.
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)'}">
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.