Building Image Gallery using AngularJS

To build your Image Gallery using AngularJS, let’s create the controller, partial and routes for it using the yeoman command as follows :

yo angular:route gallery

We will start with creating our model in the app/scripts/controllers/gallery.js file. Start with defining the various variables and arrays that we will need, within the GalleryCtrl controller function :

var pictures =$scope.pictures=[];
var baseURL="http://lorempixel.com/300/180/";
var titles=["Healthy Food","Healthy @ Work","City Life ", "Staying Fit","Looking Good","Nightlife !!"] ;
var keywords=["food", "business","city","sports","fashion", "nightlife"];
var dummyText="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed sed erat turpis. Integer eget consectetur quam. Sed at quam ut dolor varius condimentum et sit amet odio. "

First you declare an empty model called pictures.

The next variable you define is the baseURL that holds the base URL for the images that you will show in the image gallery, as you can notice in this case you are using images of width 300 and height 180.

Next, Array titles is the array containing the titles for all the images.

The keywords array holds the list of all the keywords that you will concatenate at the end of the baseURL to get relevant images for the gallery.

And finally the variable dummyText holds some lorem ipsum that we will add as a description to each of the gallery images.

Now that you have all the variables and arrays defined the next step is to create the function that will push them into the pictures model.

You will write this as follows

$scope.addPics=function(i){
pictures.push({
url:baseURL+keywords[i],
title:titles[i],
summary:dummyText
})
}

The addPics function takes in an input parameter ‘i’ which does an array push by iterating through the arrays and updating the values for the url, title and summary properties.

The final step here is to call the addPics function in a loop, incrementing the value of ‘i’ .

This is done as follows

for (var i=0;i<5;i++){
$scope.addPics(i);
}

Since for this example we need about six images we run a for loop iterating from 0 to 5. This completes our work on the controller.