Random Image viewer using AngularJS
In this post I will explain about creating random image viewer using AngularJS.
You can download the source code, from Github https://github.com/naga90/learnings/tree/angular-learnings/random-images
We are going to use Unsplash it api for getting random images from internet.
Just using https://unsplash.it/200/300 this url, will return a random image with size 200×300
If we need a square image we can use https://unsplash.it/200
In our example, we are going to use
In this url, we ask for specific image by passing image id. 400 specifies the image size.
Now we can start building our app.
Our HTML code looks like this,
<div ng-app="myFirstApp"> <div ng-controller="firstController" class="content"> <div class="form-group"> <div style="text-align:center;margin-top:10px;"> <h2>Random Images</h2> <img ng-src="https://unsplash.it/400?image={{index}}"> </div> </div> </div> </div>
And our JS File, looks like this
var myFirstApp = angular.module('myFirstApp',[]); myFirstApp.controller('firstController',function($scope,$interval){ $scope.index = Math.floor(Math.random() * 1060) + 1; });
A random image is displayed every time we reload the page. We are generating a random number between 1060 and passing it to the image source to get a random image.
Now we can include next and previous button to view next and previous image. On clicking next and previous image, we increment and decrement the index value. This will change the index value in image source, and respective image is shown.
We can also implement auto play. When auto play is enabled, we increment image index value every three seconds using interval. And it automatically displays next image every three seconds. When auto play is disabled, we can cancel the interval.
Unspalsh it also displays the image in gray (black and white) and blurred effect. To view a image in gray, we have to modify the url.
https://unsplash.it/g/400?image={{index}}
For blurred effect, we have to pass blur as GET parameter. URL will be
https://unsplash.it/g/400?image={{index}}&blur
We can toggle gray and blur effect on button click. We can change ng-src on click.
In case if some images are missing in the Unsplash it api, We can display our image on error.
onerror="this.src='img/no_image.gif'"
This will display some specific image, if ng-src has some problem in loading image.
Related Posts
Nagarajan
View Nagarajan's Profile
Latest posts by Nagarajan (see all)
- Random Image viewer using AngularJS - June 30, 2016
- Building your first AngularJS app – Shopping list - June 22, 2016
- How to use Cookies in AngularJS - October 20, 2015