Random background images with Angularjs

Asked

Viewed 93 times

2

I am using Angularjs with Ionic to make an application. On a given screen, I need to display a random image. I searched a lot here and on the internet a way to do this, but only managed with normal JS, without being in Angular and I have some doubts of how to "transform" to use in Angular.

var backgrounds = ['',
               'bg3.jpg',
               'bg1.jpg',
               'bg1013.jpg',
               'bg123.gif',
               'bg553.jpg',
               'bg663.png',
               'bgdaas3.jpg',
               'bgdw3.jpg',
               'bgdd3.jpg',
               'dasd.png'
              ];

$('#elementID').css('background','url('+backgrounds[Math.random()*10]+')');

2 answers

1

You can use the Angular ng-style attribute to apply directly, for example like this:

<div ng-style="exemplo"></div>

And then on the controller you use it like this:

$scope.exemplo = {'background' :'url('+backgrounds[Math.random()*10]+')'}

-1

It is possible with angular element., delegating an embedded Angular subset of jQuery, called jQuery lite or jqLite.

angular.element('#elementID').css('background','url('+backgrounds[Math.random()*10]+')');
  • Ohh my god! Downvote anonymous! :)

  • The downvote was not mine, but I can deduce that the reason was because his answer was in jQuery, while the OP clearly specified Angularjs.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.