How to Create Elegant Slider Carousel in Ionic Framework

Written by on August 28, 2015

How to Create Elegant Slider Carousel in Ionic Framework

Last few months I noticed a lot of people requesting a carousel example. Let’s create one, something sweet and sexy.

First of all, we will not use anything jQuery related, God knows there’s a ton of them. No, no, we’re going to do it vanilla Angular style.

Note: If this tutorial was helpful, you need further clarification, something is not working or you have a request for another Ionic post? Furthermore, leave me a comment below if you don't like something about this blog, if something is bugging you, don't like how I'm doing stuff here. Feel free to comment below, subscribe to my blog, mail me to dragan.gaic@gmail.com. Thanks and have a nice day!

Introduction

Don’t worry, we’re not going to this from scratch. Even better, I found an AngularJS based carousel made compatible with Ionic Framework. It’s called angular-swiper and it’s made on the top of the idangero.us Swiper plugin.

Angular-Swiper GitHub
Swiper GitHub
Documentation

Installation

Create a new project:

ionic start IonicCarouselDemo blank
cd IonicCarouselDemo
Warning: Since some of you never worked with Ionic CLI. From this point and further, every time I tell you to execute something, do that inside a project folder.

Before we can proceed, make sure you have the bower in your system.

npm install -g bower

Update it if you already have a preexisting installation:

npm update -g bower

Some of bower plugins require a git installation. Unfortunately, I don’t know if this plugin is one of them; my environment has everything preconfigured. Make sure you have git if you receive a git related error during this next installation:

bower install angular-swiper

Plugin and all of its dependencies can be found inside a www/lib folder.

If you’re using Cordova 4+ and especially if you’re accessing remote images don’t forget to install Cordova Whitelist plugin:

cordova plugin add cordova-plugin-whitelist

And add this security meta tag to your index.html file:

<meta http-equiv="Content-Security-Policy" content="default-src *; script-src 'self' 'unsafe-inline' 'unsafe-eval' *; style-src  'self' 'unsafe-inline' *">

Preparation

Plugin instructions are a little bit misleading, they talk about classic AngularJS preparation, we’ll do it a little bit different.

Because Ionic already wraps AngualarJS we will not need another instance.

Open your index.html and include only these files:

    <link href="lib/swiper/dist/css/swiper.min.css" rel="stylesheet"/>	
    <script src="lib/swiper/dist/js/swiper.js"></script>
    <script src="lib/angular-swiper/dist/angular-swiper.js"></script>	

Make sure these new JavaScript files are initialized after ionic.bundle.js file

Now inject ksSwiper as a dependency for your app:

var app = angular.module('starter', ['ionic','ksSwiper']);

Finally a last step. Prepare your images and add this directive to your HTML file, we’re going to do this in index.html file:

<ks-swiper-container initial-slide="3" speed="2000" loop="true" show-nav-buttons="false" slides-per-view="3" space-between="5" pagination-clickable="false" override-parameters="{effect: 'coverflow',coverflow: {rotate: 50,stretch: 0,depth: 100,modifier: 1,slideShadows : false}}">
	<ks-swiper-slide class="swiper-slide" ng-repeat="s in [1,2,3,4,5,6,7,8]">
		<img ng-src="img/puppy-{{s}}.jpg" width="100%">
	</ks-swiper-slide>			
</ks-swiper-container>

This is one of the examples I’m using in this tutorial. A link at the beginning of this article holds all configuration parameters; read them carefully.

I almost forgot. The official documentation forgot to mention one important thing. When used with Ionic, images must have a width set to 100%. Don’t do this through configuration, the carousel will stop working.

You can also use many available slide events:

app.controller('CarouselController', function($scope) {
    $scope.swiper = {};

    $scope.onReadySwiper = function (swiper) {

		swiper.on('slideChangeStart', function () {
			console.log('slide start');
		});
		
		swiper.on('onSlideChangeEnd', function () {
			console.log('slide end');
		});		
    };
});

Code

This is our final code:

HTML

<!DOCTYPE html>
<html ng-app="starter">
  <head>
    <meta charset="utf-8">
	<meta http-equiv="Content-Security-Policy" content="default-src *; script-src 'self' 'unsafe-inline' 'unsafe-eval' *; style-src  'self' 'unsafe-inline' *">	
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>

    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
	<link href="lib/swiper/dist/css/swiper.min.css" rel="stylesheet">	
    <link href="css/style.css" rel="stylesheet">

    <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
    <link href="css/ionic.app.css" rel="stylesheet">
    -->

    <!-- ionic/angularjs js -->
    <script src="lib/ionic/js/ionic.bundle.js"></script>
	
    <script src="lib/swiper/dist/js/swiper.js"></script>
    <!--<script src="../bower_components/angular/angular.js"></script>-->
    <script src="lib/angular-swiper/dist/angular-swiper.js"></script>	

    <!-- cordova script (this will be a 404 during development) -->
    <script src="cordova.js"></script>

    <!-- your app's js -->
    <script src="js/app.js"></script>
  </head>
  <body ng-controller="CarouselController">

    <ion-pane>
      <ion-header-bar class="bar-stable">
        <h1 class="title">Ionic Blank Starter</h1>
      </ion-header-bar>
      <ion-content>
		<ks-swiper-container initial-slide="3" speed="2000" loop="true" show-nav-buttons="false" slides-per-view="3" space-between="5" pagination-clickable="false" override-parameters="{effect: 'coverflow',coverflow: {rotate: 50,stretch: 0,depth: 100,modifier: 1,slideShadows : false}}"  on-ready="onReadySwiper(swiper)">
			<ks-swiper-slide class="swiper-slide" ng-repeat="s in [1,2,3,4,5,6,7,8]">
				<img ng-src="img/puppy-{{s}}.jpg" width="100%">
			</ks-swiper-slide>			
		</ks-swiper-container>
		
		<ks-swiper-container initial-slide="3" speed="2000" loop="true" show-nav-buttons="false" slides-per-view="4" space-between="0" pagination-clickable="false"  on-ready="onReadySwiper(swiper)">
			<ks-swiper-slide class="swiper-slide" ng-repeat="s in [1,2,3,4,5,6,7,8]">
				<img ng-src="img/puppy-{{s}}.jpg" width="100%">
			</ks-swiper-slide>			
		</ks-swiper-container>		
      </ion-content>
    </ion-pane>
  </body>
</html>

JavaScript

var app = angular.module('starter', ['ionic','ksSwiper']);
 
app.run(function($ionicPlatform) {
    $ionicPlatform.ready(function() {
        if(window.cordova && window.cordova.plugins.Keyboard) {
            cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
        }
        if(window.StatusBar) {
            StatusBar.styleDefault();
        }
    });
});
 
app.controller('CarouselController', function($scope) {
    $scope.swiper = {};

    $scope.onReadySwiper = function (swiper) {

		swiper.on('slideChangeStart', function () {
			console.log('slide start');
		});
		
		swiper.on('onSlideChangeEnd', function () {
			console.log('slide end');
		});		
    };
});

Deployment

Next step, we need to build our application:

ionic build android

Be careful here, this step may break if you’re behind a firewall. The first execution will take a long time, so be patient.

When this step ends, look at the output log, the last two lines should look something like this:

Built the following apk(s):
    D:\Development\IonicCarouselDemo\platforms\android\build\outputs\apk\android-debug.apk

We’ll use the last line location to deploy our application. Make sure your smartphone is prepared to accept an incoming application. In the case of Android platform, you must enable Developer Options and USB Debugging.

Do this:

adb install -r platforms\android\build\outputs\apk\android-debug.apk

or you can do this:

ionic run android -l -c -s

Download The Code

You can download this example at GitHub:

GitHub Download

Ionic View ID is: 9E15B2DB

Who Am I?

Between working as a senior Java developer in one of the largest insurance companies in the world and traveling, in my free time, I work as a professional mobile development adviser. I'm also a major jQuery Mobile supporter back at StackOverflow and a forum moderator at the official Ionic Framework forum.



Categories

34 thoughts on “How to Create Elegant Slider Carousel in Ionic Framework”

  1. Just implemented this, its awesome. Have you tried using it with the side menu? sometimes the menu opens and sometimes the carousel scrolls. Do you know if there is a was to stop the drag event for the menu, only on the Swipper element?

  2. Can someone tell me why after implementing this it shows the images in thump size and 3 at a time? or is this how it is suppose to show?

  3. Amazing.

    I tried this and it works , except I tried nesting horizontal containers on vertical ones , this doesn’t work.

    Do you have any ideas what might be the problem ?

    It works when testing on a browser , however on mobile (only tried IOS) , It doesn’t even show !

  4. Wow, It worked!!! This is so cool. Thanks a lot.

    One thing though. How can I use it as a banner slider like. I’m working on an app for a magazine brand and I need to show each banner for news headline.

    This is the first one that has worked and I’d love to build up on this. I’ve tried several before. Thanks again

      • Hi, here’s what I meant. like i said in the comment below, I have found a way to do that just by setting slides-per-view=”1″ but the issue is it does not autoplay even after setting autoplay=”5000″ except i change the screen orientation or size. The capture below is from my ripple emulator on chrome.

        Thanks for the response

    • Hi, i found a way to do the above asked question but there’s one more issue. It does not work until i change screen size. 🙁 any way out of this? Thanks

  5. Hey any idea why I cant get the slides to change? I can pull the slide to the left and see the next one but it never shows up. I even get the events called for ‘slideChangeStart’ and ‘slideChangeEnd’. But the slide never changes.

      • Yeah that makes sense. The code is pretty complicated. No errors I just try and slide and it slides right back to slide 1 even though I can see slide 2. The slides get loaded after an ajax call so I was thinking maybe I needed to update or reload the slider some how after the data is there. I’ll keep looking into it thanks anyway, nice tutorial.

  6. I have noticed that there is an issue when loading images from an external source using $http and then repeating them. The carousel opens with the main image and only starts working as expected when the page resizes? I have tried the directive suggestion in the comments but it does not work. just doing a basic ng-repeat=”item in items” and then setting the image source as ng-src=”item.imageUrl” which loads the images but displays 1 over sized image until I manually resize the window. is there a way to refresh the slider after the images load?

  7. I keep getting ‘Uncaught TypeError: Cannot read property ‘updateSlidesSize’ of undefined’ :/

  8. Great tutorial! Bravo!!!
    I have just on question…i can not activate the pagination with the bullets…i added this

    after the slides and i also set pagination=”swiper-pagination”…
    Any idea???
    Thank you very much

      • Yes but there is not error…
        this is the code i use

        is there anything wrong or something that i should add?or edit any other file?
        Thank you!!!

        • Did you ever get the pagination to show up and work? I’m trying to find out how to get this working myself. I added the and the attributes you have above but there is no pagination.

          • Well, I managed to make it appear, not sure if it is the best way but at least it is working for me:

            Add the following attribute to your <ks-swiper-container:

            pagination-is-active="true"

            this will show the pagination in the default place but if you want to display it somewhere else then also do the following:

            So, in the file angular-swiper.js look for the following code:

            angular.element(containerElement.querySelector('.swiper-pagination'))
            .attr('id', paginatorId);

            and change it for:

            angular.element(document.querySelectorAll('.swiper-pagination'))
            .attr('id', paginatorId);

            then removet this line:

            '’ +

            and place the following line wherever you want the pagination to be displayed in your dom

            Hope this helps.

  9. I’m having problems with the styling of the swiper. I added some css to swiper-container (in particoular, position:absolute and bottom:0), it doesn’t work on ionic view. With ionic serve it’s perfect on android, but on iOS is at half screen (wtf!).
    Any idea why?

  10. Thanks for this great tutorial.

    I have an issue where once i change the ng-repeat data to a variable in my controller code, I am no longer able to swipe. On an attempt to swipe, the carousel just slides back into its initial state. Also, the attributes of “initial-slide” and “slides-per-view” no longer come into affect.

    Once reverting back to an embedded data set i.e “item in [1,2,3,4]” it works as per normal.

    I have no console errors.

    Any thoughts ?

  11. Thank you, I managed to get it working using your tutorial but there are a few minor issues I’m still facing.

    1. When showing multiple slider-carousels and some of them are out of the shown page area so that the page has to be scrolled down in order to see the bottom parts, scrolling is only possible when clicking/touching in between the slides (e.g. In the margin area). When clicking and moving on slides, nothing moves.

    2. Some parameters, like freeMode do not seem to work although they are described in the official API.

    Any ideas?

  12. I have three images but only one is seen, and also not swapable. I am getting following error.

  13. Hi there!
    Excellent work! Than you for your contribution! This saves us a lot of time.
    I’m getting an unexpected behaviour on onSlideChangeEnd and slideChangeStart events.
    It doesn’t seem to trigger every time a swipe action happens. Any ideas why is this happening ?
    I have a console.log inside each one of them and I only see the active index value changing from time to time although I’m swiping.

Leave a Reply