In this post I will explain about creating random image viewer using AngularJS.
Click here to view demo
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-controller="firstController" class="content">
And our JS File, looks like this
var myFirstApp = angular.module('myFirstApp',);
$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.
For blurred effect, we have to pass blur as GET parameter. URL will be
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.
This will display some specific image, if ng-src has some problem in loading image.
Latest posts by Nagarajan (see all)