[javascript] angularjs ng-style: background-image isn't working

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 seem to be working.

<nav
    class="navigation-grid-container"
    data-ng-class="{ bigger: isNavActive == true }"
    data-ng-controller="NavigationCtrl"
    data-ng-mouseenter="isNavActive = true; $parent.isNavActive = true"
    data-ng-mouseleave="isNavActive = false; $parent.isNavActive = false"
    data-ng-show="$parent.navInvisible == false"
    data-ng-animate="'fade'"
    ng-cloak>

    <ul class="navigation-container unstyled clearfix">
        <li
            class="navigation-item-container"
            data-ng-repeat="(key, item) in navigation"
            data-ng-class="{ small: $parent.isNavActive, big: isActive == true }"
            data-ng-mouseenter="isActive = true; isInactive= false"
            data-ng-mouseleave="isActive = false; isInactive= true">

            <div data-ng-switch on="item.id">

                <div class="navigation-item-default" data-ng-switch-when="scandinavia">
                    <a class="navigation-item-overlay" data-ng-href="{{item.id}}">
                        <div class="navigation-item-teaser">
                            <span class="navigation-item-teaser-text" data-ng-class="{ small: isScandinavia }">{{item.teaser}}</span>
                        </div>
                    </a>
                    <span class="navigation-item-background" data-ng-style="{ 'background-image': 'public/img/products/{{item.id}}/detail/wide/{{item.images.detail.wide[0]}}' }"></span>
                </div>

                <div class="navigation-item-last" data-ng-switch-when="static">
                    <div class="navigation-item-overlay">
                        <div class="navigation-item-teaser">
                            <span class="navigation-item-teaser-text">
                                <img data-ng-src="{{item.teaser}}">
                            </span>
                        </div>
                    </div>
                    <span class="navigation-item-background">
                        <img class="logo" data-ng-src="{{item.images.logo}}">
                    </span>
                </div>

                <div class="navigation-item-default" data-ng-switch-default>
                    <a class="navigation-item-overlay" data-ng-href="{{item.id}}">
                        <div class="navigation-item-teaser">
                            <span class="navigation-item-teaser-text">{{item.teaser}}</span>
                        </div>
                    </a>
                    <span class="navigation-item-background" data-ng-style="{ 'background-image': 'public/img/products/{{item.id}}/detail/wide/{{item.images.detail.wide[0]}}' }"></span>
                </div>

            </div>
        </li>
    </ul>
</nav>

Though, if I do try a background color, it seems to be working fine. I tried a remote source and a local source too http://lorempixel.com/g/400/200/sports/, neither worked.

The answer is


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

The syntax is changed for Angular 2 and above:

[ngStyle]="{'background-image': 'url(path)'}"

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.


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.


It is possible to parse dynamic values in a couple of way.

Interpolation with double-curly braces:

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

String concatenation:

ng-style="{'background-image': 'url(' + myBackgroundUrl + ')'}"

ES6 template literals:

ng-style="{'background-image': `url(${myBackgroundUrl})`}"

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.


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.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to angularjs

AngularJs directive not updating another directive's scope ERROR in Cannot find module 'node-sass' CORS: credentials mode is 'include' CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 Print Html template in Angular 2 (ng-print in Angular 2) $http.get(...).success is not a function Angular 1.6.0: "Possibly unhandled rejection" error Find object by its property in array of objects with AngularJS way Error: Cannot invoke an expression whose type lacks a call signature

Examples related to angularjs-directive

Angular2 - Input Field To Accept Only Numbers Use of symbols '@', '&', '=' and '>' in custom directive's scope binding: AngularJS ng-change not working on a text input Controller not a function, got undefined, while defining controllers globally Find child element in AngularJS directive Angular directives - when and how to use compile, controller, pre-link and post-link How to validate email id in angularJs using ng-pattern Enable/Disable Anchor Tags using AngularJS get original element from ng-click How to detect browser using angularjs?

Examples related to angularjs-ng-repeat

Angular ng-repeat add bootstrap row every 3 or 4 cols ng-if, not equal to? Understanding the ngRepeat 'track by' expression Calculating sum of repeated elements in AngularJS ng-repeat Angular.js ng-repeat filter by property having one of multiple values (OR of values) Using ng-if as a switch inside ng-repeat? In Angular, how to pass JSON object/array into directive? how to split the ng-repeat data with three columns using bootstrap Preserve line breaks in angularjs ng-repeat: access key and value for each object in array of objects

Examples related to ng-style

Angular - How to apply [ngStyle] conditions Apply CSS style attribute dynamically in Angular JS How to set div width using ng-style angularjs ng-style: background-image isn't working