By now you should have a decent understanding of what a hybrid HTML5 mobile application is and how it's different to a normal native application. We've also discussed some specific frameworks that you can use to build these mobile applications like Ionic, Sencha Touch, jQuery Mobile and so on.

Now we are going to start getting into the practical side of things and building our own application. We will be using Ionic with Cordova / PhoneGap to build the application. The reason for choosing Ionic is that it has a reasonably small learning curve, it is flexible and powerful, and it is probably the most popular HTML5 mobile framework in use today.

To reiterate the different roles Ionic and Cordova serve: Ionic is used to build the majority of the application including things like the user interface, screen transitions, logic and data storage. Cordova is used to access native device API's (like the Camera) and to wrap the application up as a native application so that it can be submitted to App Stores.

Getting Started with Ionic

Before we can start building an application with Ionic we need to get everything set up on our computer first. It doesn't matter if you have a Mac or PC, you will still be able to finish this course and produce both an iOS and Android application that is ready to be submitted to app stores.

First you will need to install Node.js on your machine. Node.js is a platform for building fast, scalable network applications and it can be used to do a lot of different things. Don't worry if you're not familiar with it though, we won't really be using it much at all - we need it installed for Ionic to run properly but we barely have to do anything with it.

Installing Ionic and Cordova

Visit the following website to install Node.js:

https://nodejs.org/

Once you have Node.js installed, you will be able to access the node package manager or npm through your command terminal. You can use npm to install Ionic and Cordova by running the following command:

npm install -g cordova ionic

If everything has gone to plan, you should see a message similar to the above.

Generating an application

Once Ionic is installed, generating applications is really easy. You can simply run the ionic start command to create a new application with all of the boilerplate code and files you need.

Run the following command to generate a new Ionic application:

ionic start snapaday blank

Ionic start command

To generate a new application called 'snapaday' using a blank template (we'll talk more about what the application will be soon). Ionic comes with some templates built in, in the example above we are using the 'blank' template, but you could also use:

ionic start myApp sidemenu

or

ionic start myApp tabs

to generate an application with a sliding menu or tabs template already set up. What's really cool though is that we can also pull in a template from codepen.io that we want to use. For example you could use the following codepen.io example:

http://codepen.io/ionic/pen/AjgEB

as the base for your new application by running the following command:

ionic start myApp http://codepen.io/ionic/pen/AjgEB

We're just going to stick with a boring blank template for now though. Once your application has been generated you will want to make it your current directory so we can do some more stuff to it.

Run the following command to change to the directory of your new Ionic project

cd snapaday

If using the command prompt or terminal is new to you, you might want to read this tutorial for a little more in depth explanation.

Adding Platforms

Eventually we will be building our application with PhoneGap / Cordova, and to do that we need to add the platforms we are building for. To add the Android platform you can run the following command:

ionic platform add android

and to add the iOS platform you can run:

ionic platform add ios

If you are building for both platforms then you should run both commands. This will set up your application so that it can be built for these platforms, but it won't really have any effect on how you build the application. As I will explain shortly, most of our coding will be done inside of the www folder, but you will also find another folder in your project called platforms - this is where all of the configuration for specific platforms live.

Setting up SASS

Ionic uses SASS (Syntactically Awesome Style Sheets) to make managing the applications CSS much easier. The general idea is that instead of editing .css files directly, you will edit a .scss file that will be compiled into a normal .css file. You can use a .scss file just like you would a normal .css file, but SASS also offers a bunch of extra features like variables, nesting and mixins. Before we can use SASS we have to set it up in the application first.

Run the following command to set up SASS in your project:

ionic setup sass

In order to use SASS you must also have gulp installed, so if that command does not run successfully you may first have to run:

npm install -g gulp

and then once that has succesfully run, retry the same command:

ionic setup sass

Ionic sass command

NOTE: If you are using a template instead of a blank application, setting up SASS can overwrite required code in the index.html file so make sure you check it afterwards. If you are following this tutorial exactly though you do not need to worry.

SASS is one of those things that might confuse beginners, so if you don't really get it then don't worry too much. Just install it and pretend you're just using a normal CSS file.

Running your application

The beauty of HTML5 mobile applications is that you can run them right in your browser whilst you are developing them. But if you try just opening up your project in a browser by going to the index.html files location you won't have a very good time. An Ionic project needs to run on a web server - this means you can't just run it by accessing the file directly, but it doesn't mean that you actually need to run it on a server on the Internet, you can deploy a completely self contained Ionic app to the app stores (which we will be doing). Fortunately Ionic provides an easy way to do this.

To view your application through the web browser run the following command:

ionic serve

This will open up a new browser with your application open in it and running on a local web server. Right now, it should look something like this:

Blank Ionic App

Not only will this let you view your application but it will also update live with any code changes. If you edit and save any files, the change will be reflected in the browser without having to reload the application.

To stop this process just hit:

Control + C

when you have your command terminal open.

Upload your app to Ionic View (Optional)

You don't have to perform this step but I'd highly recommend that you do. Ionic provides an application called 'Ionic View'. You can download it from the app stores here:

iOS: https://itunes.apple.com/au/app/ionic-view/id849930087?mt=8

Android link: https://play.google.com/store/apps/details?id=com.ionic.viewapp&hl=en

This application allows you to quickly view your own applications on your device, or even send your application to others to test (which is especially handy for iOS as you don't need to worry about provisioning profiles and such - we'll talk all about those a little later).

Before you can use the Ionic View application, you will need to create an ionic.io account.

Go to ionic.io and create an account: http://ionic.io/

Once you have created an account you can login through the command line.

Login through the command line with the account you just created by running the following command:

ionic login

Once logged in, run the following command to upload your current project to Ionic View:

ionic upload

Once that has finished uploading you can open up the Ionic View application on your device, log in, and then choose your application to view it. To update your app on Ionic View you will just need to run:

ionic upload

again, and then select your application in Ionic View and choose "Sync to Latest". This will download the latest version and allow you to view it.

The Anatomy of an Ionic Project

Ok, so now we have set up our Ionic application and have a blank template to start from. Even though we're using a blank template, there's still quite a bit of code that has been set up for us already. Now is a good time to have a bit of a poke around and see how everything is working. Take a look around in the source code of the project to see if you can get some idea of what's going on.

There's many different folders and files that make up the application, but we don't need to worry about a lot of them to begin with. A lot are files that help do behind the scenes stuff and you may never even need to touch them. In fact, most of the time when we are building the app we will only be modifying what is inside the www folder (i.e. the web content), everything else is mostly related to configuration for the Ionic application or for Cordova (which is included by default). So let's focus on just the contents of that www folder for now.

index.html

Like any web page, index.html is the first file that is loaded. This file even looks like any other website you may be used to. It's responsible for including all the resources we require (like the Ionic library, all of our own Javascript files and so on) and initialising the application.

An important thing to note about this file is that people using your application will never leave it. Unlike a typical website where we might navigate from index.html to about.html to contact.html, in an Ionic application we will always be on index.html. Many Ionic applications have (and we will too) other .html templates beside the index.html, but we will never actually load those pages. When using Ionic, we are creating a single page application that uses JavaScript to switch between different views.

js

This is perhaps the most important folder. It will contain all the Javascript you write for your application. For now it only contains a single app.js file which sets up the Angular module for the app and runs a little bit of code when the application is loaded and ready.

The most important thing to note about the app.js file is this line at the top:

angular.module('starter', ['ionic'])

What this does is create an AngularJS application called 'starter' and it includes the Ionic functionality in that app. Ionic is built on top of AngularJS, to put it simply an Ionic application is an AngularJS application with a bunch of extra features to make creating mobile applications easier.

Now if you look at the body tag in your index.html file you will see this:

<body ng-app="starter">

This attaches the Angular application that was just created to the body tag. You can attach the application to any tag you like simply by using the ng-app directive.

Our application isn't called "starter" though, it's called snapaday! So let's go ahead and make that small change.

Edit your app.js file and make the following change:

angular.module('snapaday', ['ionic'])

Edit your index.html file and make the following change:

<body ng-app="snapaday">

In future we will be adding to this file quite a bit, as well as creating additional files for other modules that we will create for our controllers and services. Most people who read this course will likely be new to AngularJS so I will explain concepts as we go, but if you want a bit of a leg up then you can read this post where I give a bit of a crash course introduction to AngularJS.

lib

This folder contains all of the Angular / Ionic libraries that our application will make use of. This is basically the engine for our application, but fortunately we'll never really have to touch anything in this folder.

templates

The templates folder will contain HTML templates that are being used throughout the application. We have one problem though, it doesn't exist yet. It's really important to have some structure and organisation in your application as it grows. You could place just about everything in your app.js file and your index.html file, but your application would quickly become ugly and unmanageable. Very shortly we will create a templates folder and create our very own template.

css, images

These folders contain the css and image resources for our application. I mentioned setting up SASS in the previous lesson, the css folder is where the css files SASS generates will be stored. To modify the css we will be editing the ionic.app.scss file located in the scss folder (which is in the root directory of your project) but we will get to how to do this later.

As I mentioned above, there's a lot more files and folders that we haven't discussed yet. At this stage it's not important to understand what they do, as they become useful to us and we begin to make modifications here and there it'll be easier to understand rather than overwhelming you with information now.

Introducing Snapaday

We will be modifying and adding to this starter application until it becomes the app that we want to build... which is what exactly?

I wanted something that was relatively easy, touches on most of the core concepts of Ionic, and is a little more fun and original than a todo list or note taking app.

The example application that we will be building in this course will encourage users to take a photo each day, and then create a slideshow that displays all of their photos in succession, kind of like this video.

Through building this application you will learn:

The application will consist of two main views. The first view will contain a list of all the photos that have been taken, and will provide the following options:

If a user chooses to 'Play photos' this will launch the second screen which will display the slideshow to the user. On this screen they will have the option of replaying the slideshow or exiting from it.

Here's what the various screens will look like when it is finished:

Snapaday Screenshot

Snapaday Screenshot

Snapaday Screenshot

Let's get started!

We're going to take some baby steps to start off with by making sure we create a nice, scaleable structure for our application. In the next lesson we'll get into some more serious stuff, but there's nothing more important than having a strong foundation to build on top of.

There's a few different ways to organise an Ionic application, technically you can do it anyway you like that works, but we will be implementing one approach that is reasonably popular and simple.

NOTE: We will be building the entire application step by step. If you follow each of the instructions that are:

highlighted like this

then you should end up with the final product. There's a lot of steps though and chances are something will go wrong at some point. In your download package you will have received the source code for this application, split into various lessons. If you ever get stuck or something isn't working quite right, just compare your code to the sample code in "snapaday-lesson-0X".

To start off with we're going to create a templates folder that will hold the HTML templates for all of the different views within our application.

Create a new folder inside of www called templates

Ionic Project Structure

Modify the code in your index.html file to look like the following:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>

    <!-- compiled css output -->
    <link href="css/ionic.app.css" rel="stylesheet">

    <!-- ionic/angularjs js -->
    <script src="lib/ionic/js/ionic.bundle.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-app="snapaday">

    <ion-nav-bar class="bar-light">
        <ion-nav-back-button>
        </ion-nav-back-button>
    </ion-nav-bar>

    <ion-nav-view></ion-nav-view>   

  </body>
</html>

We've made a little change to the header here, but the most important thing to note is the inclusion of <ion-nav-view>. The easiest way to explain this is to imagine it as a placeholder for our templates. We could create a template called template1.html and trigger it to be displayed with this <ion-nav-view> at some point, and then we could have another template2.html which we could switch to and then that would be displayed instead. Let's create our first template.

Create a new file called main.html inside of the templates folder and add the following code to it:

<ion-view hide-back-button="true" view-title="Main View">
  <ion-content>
    I'll do something cool soon enough!
  </ion-content>
</ion-view>

To create templates that will be displayed inside of we use . By supplying a view-title we can dynamically change the header in index.html and we can also control whether or not we want to display a back button so that the user can navigate back to the view that they came from previously.

If you take a look at your application by running ionic serve now you will see:

Blank app

Oops... now we can't see anything. We've set up the and a template to be displayed inside of it, but how is our application supposed to know what we want to display? We can do this using routes.

Modify your app.js file to look like the following:

angular.module('snapaday', ['ionic'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if(window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }
  });
})

.config(function($stateProvider, $urlRouterProvider) {

  $stateProvider
  .state('main', {
    url: '/main',
    templateUrl: 'templates/main.html',
    controller: 'MainCtrl'
  });

  $urlRouterProvider.otherwise("/main");

});

You will notice that we have added a config that is injecting the $stateProvider and $urlProvider services. These services are provided by default and can help us handle routes within our application (a route is essentially a way to map URLs to views). By "injecting" these services (which means we have included them as parameters) we make the service available within the scope that it is being called from. I don't want to get too technical just yet so don't worry if you don't really get what all this means, we will continue injecting and using services throughout our application and it will become easier to see how it all works.

In the code above we are creating a state called main. A state is the state that your application is in, for example you might have a main state, an introduction state, and a login state within your application. Each of these states can have different templates attached to them, which we specify through the templateUrl.

The url is used to determine when this state should be active, in this case it has a URL of /main so if our application is currently pointing to:

localhost:8100/#/main

Then the main state will be shown. This allows us to link (similar to how you would on a normal website) to different states very easily. If the current route does not match anything we have listed then it will default to /main since we have specified:

$urlRouterProvider.otherwise("/main");

Finally we've supplied a controller. A controller can be considered somewhat like a director or traffic controller in your application. For example if you want something to happen when somebody taps a button, then you would create a function in your controller to do this and you would call it from one of your templates. By specifying a controller for this state, we are saying that we want this controller associated with this template. So if we create a function called doSomething() in our Main controller then we can call that function from our main.html template. But if we were to create another template with a different controller then we could not call that function (you can however use the same controller for multiple templates).

If we try to view our application now we're still going to be running into problems. We've assigned a controller to our state but it doesn't exist yet, so now we're going to have to create that.

Again, we could place this controller in the app.js file but we want to keep our code organised. So we're going to create an additional two files: controllers.js to hold all of our controllers and services.js to hold all of our services. We don't have any services just yet, but we do want to create our Main controller, so let's do that.

Create a new file at **www/js/controllers.js* and add the following code:

//This creates a new module called 'controllers' that will hold all of the controllers for our app
angular.module('controllers', [])

.controller('MainCtrl', function($scope, $state) {

  console.log('MainCtrl');

});

In the code above we've created our Main controller (which doesn't do a whole lot just yet). Notice that in controllers.js we are creating a new angular.module just like we have in app.js. An Ionic app is made up of lots of modules: the app itself is a module, controllers are modules, services are modules and so on. Modules are great because it allows us to separate code which makes it organised and reusable. Although we don't have a service we want to create yet, let's get our services.js file set up anyway.

Create a new file at www/js/services.js and add the following code:

angular.module('services', []);

We also need to include our new controllers and services modules in the apps main module. To do this we supply the controllers module and the services module as a requirement for the main module.

Add the controllers and services modules as a requirement in the apps main module in app.js:

angular.module('snapaday', ['ionic', 'controllers', 'services'])

And finally, we also need to include these new files we've created in our index.html file.

Add the following references to index.html

    <script src="js/app.js"></script>
    <!-- Make sure to include any new javascript files you create -->
    <script src="js/controllers.js"></script>
    <script src="js/services.js"></script>

Run ionic serve to test your application in the browser (you can have this running constantly in the background) and make sure you see the following:

Ionic Starter App

If something has gone wrong then try taking a look around the source code to see if you can find out what's wrong. Make sure to check the 'Console' in your debugging tools as a first step (Right Click > Inspect Element > Console), as often it will tell you where the error is. If you can not figure out what's wrong, then compare your code against the code for Lesson 1 that was supplied with this course. We will discuss some more ways to debug your applications in a later lesson.

We have a reasonably scaleable and easy to understand application structure now. Even this structure will become unmanageable if the application is too large or complex though. You could further break down the controllers module into individual controllers (rather than having all of your controllers in one file) or use one of the methods discussed in the homework tasks below. As a beginner though, this is a great structure to start off with.

In the next lesson we will start getting our hands dirty and creating a lot more code of our own by building out the views for our application. We've made a pretty good start already in the first lesson, so far we have:

This gives us a really nice base to work off of moving forward. At this point we have a pretty generic starter application with our development environment set up and ready to go. You would repeat these steps for just about every new Ionic app that you want to create (except for the things we had to install of course).

As we build the application and come across new concepts, I will explain everything as it comes up. So don't worry if you don't have any idea what you're doing yet (that's pretty much the idea anyway!).

Homework Tasks

Copyright © 2015 Joshua Morony | Privacy Policy | Contact

This is a preview of Mobile Development for Web DevelopersLEARN MORE