1

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

4
  • if you want a background image don't use a <img /> tag, use the div and use ng-style to bind the scope data to the html attribute Commented Aug 3, 2016 at 13:59
  • use ng-src not src Commented Aug 3, 2016 at 14:01
  • Use "url("+images[counter]+")" Commented Aug 3, 2016 at 14:01
  • @Daniel_L yes, I mentioned about the img tag which i found in the dom inspector. I did not use it in my code. Commented Aug 3, 2016 at 14:16

2 Answers 2

1

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");
});
Sign up to request clarification or add additional context in comments.

Comments

0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.