An Introduction to the Ionic Framework

0
10001

Main

Ionic is an advanced HTML5 hybrid mobile application framework. Using Apache Cordova, it can be easily run on mobiles. A big advantage of using Ionic is that the code base remains the same for all mobile platforms and the UI/UX looks like a native mobile platform.

Developing mobile applications is easy if we are only targeting one platform, but that’s not the case with many organisations. Mobile applications for all platforms are difficult to maintain and create, as we need a different code base for each platform (Android, iPhone, Windows), and the UI/UX should be the same for all. Each platform comes with its own set of tools and languages like Java for Android, XCode for Apple and Windows SDK for Windows phones. And each has its own IDE to work on. Instead of building the apps for all platforms separately, many frameworks or tools allow an application to be developed once, to be used on any platform. Usually, this tool or framework uses HTML and CSS for the UI/UX part.
Ionic is one such framework that uses HTML5 for the UI/UX part. It is built on HTML, JS and CSS, which contain UI elements in different forms to suit specific platforms.  Being an HTML framework, we can run the Ionic application in a browser very easily, but to run it on a mobile, Ionic uses Cordova, an Apache product, which allows it to access the native features of mobiles like Contacts, Camera, etc. So, Ionic is a mobile application development framework used to build hybrid apps or mobile applications. It uses HTML5 for developing the mobile applications. A hybrid app is a website running in a browser shell in an app that has access to the native platform layer. Compared to pure native apps, hybrid apps shine in terms of more platform support, ease and speed of development, and easy access to third party code.
As per its website, Ionic is like ‘Bootstrap for Native’. It is a UI framework that handles the user interface and its interaction. Ionic comes with native style UI elements and layout.
A big advantage of using Ionic is that the code base remains one for all mobile platforms and the UI/UX looks like a native mobile platform. Ionic also uses AngularJS. It provides many directives for the Angular App.

Note: While developing mobile applications, do ensure that you have the Android SDK downloaded and configured. Similarly, at least one Android virtual device should also be configured. The same applies to iOS. Besides this, you also need a working Internet connection.

Figure 1
Figure 1: Starting a new blank project

Installing and configuring the Ionic framework
All the examples and installations are done on an Ubuntu machine, though we can do the same on Windows or Mac machines, given that some commands for installation will differ. So all apt-get commands mean we are installing some packages or libraries. On Windows and Mac, the same can be downloaded and installed. A terminal in Ubuntu is the same as the command prompt in Windows.
The first step is to install Node.js and npm.
On a Linux machine, open the terminal and execute the following command:

$ sudo apt-get install nodejs npm

Before we move ahead, let’s add npm auto complete in our bashrc file. This step is not compulsory, though.

 $ npm completion >> ~/.bashrc
$ source ~/.bashrc

Let’s install Ionic by executing the following commands, one by one:

$ npm install cordova gulp
$ npm install ionic

In the current working directory, you can see the folder name node_modules, which will have all that has been downloaded.
The next step is to configure the path for the mobile SDKs. For Android, we need to configure ANDROID_HOME to point to the location of the Android SDK, and add platform-tools and the tools’ path of the SDK to the PATH environment variable. Use the set command to set both the paths. Once that’s done, use the echo command to verify the same, as shown below:

$ ashish@ashishwork:~$ echo $ANDROID_HOME
/home/ashish/android/sdk
$ ashish@ashishwork:~$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/home/ashish/android/sdk/platform-tools:/home/ashish/android/sdk/tools
Figure 2
Figure 2: Output of myContact app in browser
Figure 3
Figure 3: Ionic prompt

Building a demo application using Ionic
To start the application, Ionic provides three basic blank templates, tabs and a side menu. We will start with the blank template. Open a terminal and run the following command:

$ ionic start myContact blank

This will get the blank project from the Net on to the local machine and configure it. Also, Cordova will get configured for the new application.
When asked to create the ionic.io account, type n for no, to skip the account creation as shown in Figure 1.
This will create a folder named myContact in the current directory; move to myContact using cd myContact. As mentioned in the introduction, since Ionic uses HTML5, we can test the output in the browser directly. In the terminal window, since we are already in the myContact path, type the command ionic serve and press Enter, which will open the browser with the myContact app as shown in Figure 2.
Coming back to the terminal, you will see the prompt changes to ionic $, as shown in Figure 3.
Change the files and refresh the browser to see the changes. There’s no need to compile or build the application. Once we are done with changes, press q on the terminal to return to a normal prompt. For now, press q in the terminal window.
Before moving ahead, let’s build the application and test it on the emulator. In a terminal, execute the following command:

$ cordova platform add android
$ ionic add platform android
$ ionic build android
Figure 4
Figure 4: Output of my-contact on the emulator
Figure 5
Figure 5: Listing of mycontact folder

The last command will start the Android emulator and will run the app, as shown in Figure 4.
Let us explore the myContact folder, where we can see many files and folders (Figure 5).
Let’s quickly understand what each file and folder is used for.

  • bower.json stores the bower dependencies
  • config.xml stores the configuration for Cordova
  • gulpfile.js stores the gulp task
  • hooks stores the Cordova hooks for executing a specific command
  • ionic.project stores the Ionic configuration
  • package.json stores the dependencies for Node
  • platforms stores the mobile platform, i.e., Android, iOS, etc
  • plugins stores the plugins
  • scss stores and is used in CSS
  • www is the application folder which stores HTML, CSS, JS, etc

Let us change the application to show some output. We will do it in two steps — first displaying some static data, and then displaying dynamic data. In the www folder, we can see index.html generating our output, and in the js folder, app.js is used for interaction. Open the index.html and app.js files in editing mode [edit, Vim, Notepad, etc]. First, we will change the header text. In index.html, locate the body tag and replace the text Ionic Blank Starter with My Contacts. Locate the <ion-content> tag, and add the following code after the tag:

<ion-list>
      <ion-item ng-repeat=”contact in contacts”>
        {{contact.title}}
      </ion-item>
</ion-list>

Just to be clear, we are using ng-repeat of AngularJS, which is nothing but a kind of loop and will print all the contacts titles on the page.
In the app.js file, add the following line after angular.module(‘starter’, [‘ionic’]):

.controller(‘MyContactCtrl’, function($scope) {
  $scope.contacts = [
    { title: ‘Ashish Bhatia’ },
    { title: ‘Friend 1’ },
    { title: ‘Friend 2’ },
    { title: ‘Friend 3’ }
  ];
})

We have defined a controller named MyContactCtrl and created a contact with some data. We need to add this controller to index.html. In the index.html file, add the controller in the body tag, which will look like <body ng-app=”starter” ng-controller=”MyContactCtrl”>. Save both the files, index.html and app.js.
In a terminal window, execute the command ionic serve, which will open the browser as shown in Figure 6.
When you move back to the terminal, you will see the Ionic command prompt. Press q to return to the normal prompt. To test this on an emulator, execute the following commands:

$ ionic build android
$ ionic emulate android
Figure 6
Figure 6: Ionic server output

The last command will launch the emulator, as shown in Figure 7.

Figure 7
Figure 7: myContact data output on the emulator

The data displayed is static as we have hard coded it in the js file. To make it dynamic, we need to add a button for New, which will display an input form for the title and will display it in the list.
Again, open the index.html and app.js files for editing.
In the index.html header part where we have added My Contact in the h1 tag, add a button for New as shown below:

<button class=”button button-icon” ng-click=”newContact()”>
        <i class=”icon ion-compose”></i></button>

This will create a new button option in the header part.  We need to create the input form for accepting user inputs. Add the following code before the </body> tag:

<script id=”new-contact.html” type=”text/ng-template”>
<div class=”modal”>
    <!-- Modal header bar -->
    <ion-header-bar class=”bar-secondary”>
      <h1 class=”title”>New Contact</h1>
    </ion-header-bar>
 
    <!-- Modal content area -->
    <ion-content>
      <form ng-submit=”createContact(contact)”>
        <div class=”list”>
          <label class=”item item-input”>
            <input type=”text” placeholder=”Enter name of Contact” ng-model=”contact.title”>
          </label>
        </div>
        <div class=”padding”>
          <button type=”submit” class=”button button-block button-positive”>Create Contact</button>
        </div>
      </form>
    </ion-content>
  </div>
</script>

We are again using AngularJS here. We have created a template for input in a script tag, which will be controlled by the controller. To add a controller, open app.js and add the following line before the .run line in the file:

// Create and load the Modal
  $ionicModal.fromTemplateUrl(‘new-contact.html’, function(modal) {
    $scope.contactModal = modal;
  }, {
    scope: $scope,
    animation: ‘slide-in-up’
  });
 
  // Called when the form is submitted
  $scope.createContact = function(contact) {
    $scope.contacts.push({
      title: contact.title
    });
    $scope.contactModal.hide();
    contact.title = “”;
  };
 
  // New contact modal
  $scope.newContact = function() {
    $scope.contactModal.show();
  };
 
  // Close the new contact modal
  $scope.closeNewContact = function() {
    $scope.contactModal.hide();
  };
})
Figure 8
Figure 8: myContact new output in browser
Figure 9
Figure 9: New contact form
Figure 10
Figure 10: myContact updated list

Try to look at the methods, which are self-explanatory. When we click on a new button on the header, a new-contact.html will be displayed with a form. Type the contact name in this form and click on the Create Contact button. This will close the new-contact.html form and will update the contact list on the main UI screen.
To test the application in the browser, run the ionic serve command in a terminal, which will open the browser as shown in Figure 8.
Click on the New button shown on the right top corner, which will open the form we created, as shown in Figure 9.
Fill in the data and click on Create Contact which will close the form and display the data on the mail application page, as shown in Figure 10.
Let’s run it on the emulator. In terminal windows, press q to return to the normal prompt and execute the following commands:

$ ionic build android
$ ionic emulate android
Figure 11
Figure 11: myContact output on the emulator
Figure 12
Figure 12: myContact app new contact form
Figure 13
Figure 13: myContact output with contacts

The last command, as usual, will launch the emulator, as shown in Figure 11.
Click on the New button and add the data, as shown in Figure 12.
Add some more data in the same way, and we can see all that was added displayed on the main screen (Figure 13).
The Ionic framework has many other UI/UX controls. You can see how easy it is to build an application using Ionic. If you want to run the same application on iOS, install the iOS SDK, replace the Android commands with iOS commands, and our iOS application is ready. For more information, refer to the Ionic website which contains CSS components, books, demos and much more.

LEAVE A REPLY

Please enter your comment!
Please enter your name here