Create a slideshow by using AngularJS

Hi guys! In this tutorial I will explain how you can easily create a sample slideshow by using AngularJs.

To create a slideshow, I have writed this code:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<style>
#slide{
width: 200px;
height: 200px;
overflow: hidden;
position: relative;
}
#slideshow ul{
margin: 0px;
padding: 0px;
}
#slideshow li{
list-style: none;
height: 200px;
width: 200px;
}
#slideshow img{
max-height: 200px;
max-width: 200px;
}
</style>
</head>
<body ng-app>
<div ng-controller="MySlideshow">
<div id="slide">
<div id="slideshow">
<ul id="ul">
<li><img src="a.jpg"></li>
<li><img src="b.jpg"></li>
<li><img src="c.jpg"></li>
</ul>
</div>
</div>
<input type="button" value="Next" ng-click="next()">
</div>
<script language="javascript">
function MySlideshow($scope)
{
var i = 1;
$scope.next = function()
{
var length = document.getElementById("ul").children.length; // this code will calculate the number of images
if(i < length)
{
var top = i * 200;
document.getElementById("slideshow").style.marginTop = "-"+top+"px";
i++;
}
}
}
</script>
</body>
</html>

I have writed this styles to set the size of images and remove the space:

<style>
#slide{
width: 200px;
height: 200px;
overflow: hidden;
position: relative;
}
#slideshow ul{
margin: 0px;
padding: 0px;
}
#slideshow li{
list-style: none;
height: 200px;
width: 200px;
}
#slideshow img{
max-height: 200px;
max-width: 200px;
}
</style>

I have writed this html code to display the images:

<div ng-controller="MySlideshow">
<div id="slide">
<div id="slideshow">
<ul id="ul">
<li><img src="a.jpg"></li>
<li><img src="b.jpg"></li>
<li><img src="c.jpg"></li>
</ul>
</div>
</div>
<input type="button" value="Next" ng-click="next()"> // this button will call next image
</div>

Next, I have writed this code to change the images:

<script language="javascript">
function MySlideshow($scope)
{
var i = 1;
$scope.next = function()
{
var length = document.getElementById("ul").children.length; // this code will calculate the number of images
if(i < length)
{
var top = i * 200;
document.getElementById("slideshow").style.marginTop = "-"+top+"px"; // this code will move the images up and it will display the next image
i++;
}
}
}
</script>

I have created also a video tutorial:









Leave a Comment