Nurul Alam
Nurul Alam

Reputation: 352

dynamic background image with angularJS javascript

i am loading some images into DOM and creathing an array to hold these images. I want to dynamically change background image of a div called wrapper from collecting image from the array. How to do this?

Now I have this

$scope.$on('$viewContentLoaded', function() {
    $rootScope.backgroundImg="url('http://abounde.com/uploads/images/office.jpg')";   
    $rootScope.loading = false;
    console.log("about page loaded");
});

I want something like this

var images =[imageObject1, imageObject2, imageObject3];  
//imageObject are already loaded and when i 
//call them inside a html div using .html(), 
//they show as <img src="source of the image"/>

$scope.$on('$viewContentLoaded', function() {
    $rootScope.backgroundImg="url('images[0]')";   
    $rootScope.loading = false;
    console.log("about page loaded");
});

I can create object and store them in array. I just need to have a way to use thsee image in the backgroundImg variable which sets the background style of a div

Upvotes: 1

Views: 1431

Answers (2)

Jorge Alberto
Jorge Alberto

Reputation: 177

First you need to put your array of images url at scope:

$scope.$root.images = ['imageurl', 'imageurl1', 'imageurl2']; 

At HTML you need to put

ng-style="{'background-image': 'url({{ $root.images[0] }})'}

This will work!

Upvotes: 0

Ismail RBOUH
Ismail RBOUH

Reputation: 10470

You can use ngStyle :

<html ng-app  ng-style="htmlStyle">
    <!-- Html here -->
</html>

Then:

var images =[imageObject1, imageObject2, imageObject3];
var currenBackground = 0;
$scope.$on('$viewContentLoaded', function() {
    var current = currenBackground++ % images.length;
    $rootScope.htmlStyle = {
       backgroundImage: "url("+ images[current].src +")"
    };   
    $rootScope.loading = false;
    console.log("about page loaded");
});

Upvotes: 1

Related Questions