Random image background with AngularJS

2

I'm using AngularJS with Ionic to make an application. On a particular screen, I need to display a random image. I've tried a lot here and on the internet a way to do this, but I only managed with normal JS, without being in Angular and I have some doubts about 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]+')');
    
asked by anonymous 20.01.2017 / 17:53

2 answers

1

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

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

And then in the controller you use like this:

$scope.exemplo = {'background' :'url('+backgrounds[Math.random()*10]+')'}
    
20.01.2017 / 18:55
-1

It is possible with angular.element , which delegates a built-in subset of Angular jQuery, called jQuery lite or jqLite .

angular.element('#elementID').css('background','url('+backgrounds[Math.random()*10]+')');
    
20.01.2017 / 18:17