Nurul Alam Anik Nurul Alam Anik - 4 months ago 24
AngularJS Question

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

Answer

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");
});
Comments