Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Ionic Framework: How to create Hybrid Apps

See in this article how to create hybrid apps with the Ionic Framework and also learn how to use this framework.

What Is Ionic?

Ionic is an MIT-licensed, front-end framework for creating hybrid mobile apps. Ionic is also a Node module that helps with the process of creating, building, and packaging hybrid apps. The Ionic framework and module are backed by the same company, Drifty". In the context of this article, Ionic will be used in both cases. Either way, Ionic empowers developers to leverage their AngularJS and HTML5 skills to create beautiful, high-performing apps.

Setting Up Ionic

Ionic relies on Node.js. For that reason, you must install Node.js if you haven't done so previously. You can get the Node installer from http://nodejs.org/. Once installed, Ionic can be installed using Node's package manager (npm) via the following command-line command:

npm install -g cordova ionic

Snippet A

The preceding command will install the Ionic and Apache Cordova modules globally. We'll discuss Apache Cordova later. For now, understand that these modules get registered as command-line commands. The modules themselves are installed in your user directory. If you're running Windows, the modules are at C:\Users\{username}\AppData\Roaming\npm. If you're running Mac OS X or Linux, the modules can be found in /usr/local. Either way, once Ionic is installed, you're ready to create a project.

Creating an Ionic Project

Creating a project with Ionic is as easy as running a single command-line command. With your console window open, enter the following:

ionic start myApp blank

Snippet B

The command in Snippet B relies on the Ionic module installed in Snippet A. The second argument (start) tells Ionic that you want to start a new project. The third parameter specifies the path to initialize the project in. For the sake of this article, we'll do all of our work in the current directory. Finally, we have the option of choosing a template to help jump start development. The available templates at this time, and a preview of each, are listed below:

blank

A project created with this template will generate an app that has a single view to start.

HeroUnitExample.

sidemenu

A project created with this template will generate an app with multiple views to start. The views can be navigated to via the hamburger menu in the upper-left corner.

HeroUnitExample.

tabs

A project created with this template will generate an app with multiple views to start. The views can be navigated to via the tabs at the footer of the app.

HeroUnitExample.

These options vary based on the navigation needs of an app. For the sake of this article, we'll stick with the blank template and build up from there. To see the app running, you have options of how to run an Ionic project.

Running an Ionic Project

If you look in the myApp directory created with Snippet B, you'll notice that a lot of stuff is generated for you. In fact, as of the time of this writing, 137 files (~44MB) got created! We'll look at these contents in detail later. Before digging into the contents, though, let's see this basic app running. You have two options: run the app in the browser or run on a native platform.

Running in the Browser

Ionic apps are built with web technologies. You can develop, debug, and test Ionic apps in the WebKit browser of your choice. Browsers that support WebKit include Apple Safari, Google Chrome, and the Opera browser. To open an Ionic app in one of these browsers, you need to host the app in a web server. Thankfully, Ionic comes with one.

Ionic lets you run your apps locally via LiveReload. LiveReload is a server that gets installed as a Node module. This module was installed when a snippet was run. The specifics of LiveReload are beyond the scope of this article. Still, to run your Ionic app, you can enter the following command in your command line:

ionic serve

Snippet C

Once you run the command in Snippet C, you should see the app running in your default browser. To see the really cool part, though, make a code change. For example, open the myApp/www/index.html file in your favorite text editor. Change the code that says class="bar-stable" to class="bar-positive". Now, look in your browser. The app has automatically updated. In fact, it probably updated before you could switch to your browser. This is the magic of LiveReload. To go even further faster, let's open the developer tools.

If you're running Google Chrome, open the developer tools by pressing Ctrl+Shift+J on Windows or Control-Option-I on a Mac. Once opened, click the Emulation tab at the bottom of the Tools pane. Choose a device, click emulate, and refresh your browser. Voilà! Your app is running on a simulated device, in your browser. My setup looks like this:

Running your app on a simulated device.

Figure 1. Running your app on a simulated device.

You can get pretty far along developing your app in your local browser. However, your app may need to use features that are more readily available on a real device. For example, your app may make use of an accelerometer or a compass. These capabilities are more likely to exist on your phone than the machine you're cranking code on. For that reason, we need to discuss running apps on native platforms.

Running on a Native Platform

Running apps built with the Ionic framework on a native platform requires Apache Cordova. Cordova is an open source library that makes device-level APIs accessible to JavaScript. In other words, things like the accelerometer or compass become programmatically accessible through JavaScript. This bridge helps you cross the divide between physical hardware and more malleable software. If you ran the command in Snippet A, Cordova was installed at the same time as Ionic.

The Ionic module makes it simple to target platforms when you're ready to start testing and deploying your app on specific platforms. From the command line, you enter ionic platform add  to prepare your app for a specific environment. For example, if you want your app to run on the three most popular mobile platforms (Android, iOS, and Windows Phone), you can run the following from the command line:

Note: Will only work on a Mac OS X machine.

ionic platform add android
ionic platform add ios
ionic platform add wp8

Snippet D

Each of the commands in Snippet D is run independently of each other. If you run any of these commands, there is a chance you may get errors. If you receive an error, it most likely means you don't have the related SDK installed. Once you have added the platforms you want to target, you can build your project for a given platform as shown in Snippet E:

Note: Will only work on a Mac OS X machine.

ionic build android
ionic build ios
ionic build wp8

Snippet E

Building your Ionic app creates a package using the SDKs installed on your local machine. You have the option of using the package task instead. That task uses the Ionic Build service to create app-store ready bundles without using SDKs on your local machine. This is especially useful if you're creating apps on a Linux or Windows machine and want to pump out an iOS app. The details of the Ionic Build service are beyond the scope of this article. There are two other libraries you should be aware of when building your Ionic apps.

The two libraries that will help you build apps with Ionic are called http://ngcordova.com/ and http://www.ecofic.com/about/blog/introducing-ng-cordova-mocks. ngCordova is a set of extensions that bridge the gap between AngularJS and Cordova. As Ionic makes heavy use of AngularJS, these extensions may become an integral part of your development. ngCordovaMocks complements ngCordova in that it empowers you to continue developing and testing your app in a web browser. These libraries are optional, but highly recommended.

Once you've created your application packages, you might want to run them. You have several options. The two most popular include running the package in a simulator or on a physical device.

Running in the Simulator

Running your app in a simulator can be more convenient than running it on a physical device. Ionic makes it easy to run your app in a simulator from the command line. To fire up your app in a simulator, you can run one of the following commands:

Note: Will only work on a Mac OS X machine.

ionic emulate android
ionic emulate ios
ionic emulate wp8

Snippet F

Running your app in a simulator will get you closer to the real thing than the previously mentioned browser emulation. However, there's nothing better than the real thing. For that reason, you should consider running (and testing) your app on a real physical device.

Running on a Physical Device

To run your app on an actual physical device, you use the run task. This task can be executed by entering the following into the command line:

ionic run --device

This task requires the --device argument to deploy to run the app on a physical device. Once run, this task builds the project, creates the application package, and deploys the app to a connected physical device. From there, you can continue your testing.

Using the Ionic Framework

Now, we will focus on the Ionic command-line tools. This article will focus more on the Ionic Framework itself. After reading this article, you'll have a better feel for what Ionic provides. To be comfortable with the contents of this article, you should have a basic understanding of AngularJS, CSS, and HTML. To show some of Ionic's capabilities, we will build a todo app. The app will look like the following:

The completed todo list.

Figure 2. The completed todo list.

This app is based on an MIT-licensed app. The purpose of this article is to talk about Ionic, not re-invent the wheel. The app itself is very basic. It lets you simply add to-do items. Editing and deleting items are out of scope for this article. That's because is we want to stay focused on the unique piece: the Ionic framework. To jump start the process, run the following commands in an empty directory from your command line:

ionic start todo blank cd todo npm install ionic serve 

Code Segment A

The four commands in Code Segment A will initialize a new app. This basic app should be open in your web browser. The commands in Code Segment A were discussed in the previous article. With the tooling in your belt, we can change focus to actually develop an app. To make an app that looks like the one in Figure 1, we'll start by adding some tabs for navigational purposes.

Adding Tabs to Your App

The first thing we'll do is add two tabs to our app. If you would like to follow along, open www/index.html in your favorite text editor. Replace the code that says with the following:

<ion-tabs class="tabs-background-positive tabs-icon-top">
   <ion-tab title="Items" icon="ion-document-text">
      <ion-content>
         Tasks go here
      </ion-content>
   </ion-tab>

   <ion-tab title="Details" icon="ion-information-circled">
      <ion-content>
         Details go here
      </ion-content>
   </ion-tab>
</ion-tabs>

Code Segment B

The code in Code Segment B creates two tabs within the app. The ion-tabs element is an AngularJS directive used to allow multiple items to share the same real estate on the screen. By default, the tabs will position themselves against the bottom of the screen. However, you can choose to add the tabs-top class to position the tabs against the top of the screen. The other two classes used in the snippet above, tabs-background-positive and tabs-icon-top, are just as interesting.

Setting Tab Icon Position

The colors used in the tabs can be customized with the help of two separate classes: tab-background-{color} and tab-{color}. The former class specifies the tab's background color. The latter class identifies the class to use in the foreground. In the example above, you may have noticed the word positive is used for the color. This is pulled from the list of predefined colors specified at http://ionicframework.com/docs/components. You can define your own colors if you so choose.

The other class used above, tabs-icon-top, was used to specify the use of icons in the tabs. By default, tabs will only show their text. If you want to actually show an icon, you need to specify the icon's location in relation to the text. This can be set with one of the pre-packaged CSS classes. Those classes and a brief description are shown in Table 1:

Options for positioning tabs.

Table 1 shows the options for positioning tabs. There are also options to set the tab colors.

Setting Tab Colors

Tabs in a single app usually have a shared look-and-feel. The Ionic framework makes it easy to customize the colors used. You can quickly set the colors by using the tab-{color} class. This class will let you set the color of the tab bar. The {color} piece is one of the predefined colors mentioned before. There are ways to use your own custom colors by using class CSS skills.

Setting tab colors is a great way to make your app stand out. Using icons is a great way to make your app more approachable. To understand the other customization options at the tab strip level, I would recommend reviewing the documentation available at http://ionicframework.com/docs/components/. For now, it's time to narrow our focus and look at individual tabs.

Working with Individual Tabs

Each tab represents a selectable item within a tab strip. This selectable item is created by the ion-tab directive seen in Code Segment B. When selected, the content associated with the tab will appear. We'll get into creating some content a little later. For now, let's discuss the title, icon, and badge options available for an ion-tab at design time.

The title attribute lets you set the name of a tab. This name will be shown as long as the tab-icon-only class is not added in the parent ion-tabs directive. It's recommended to keep the title attribute value to a single, short word. Be brief and be bright.

The icon for a tab can be set through the icon property. This property relies on a string that identifies a CSS class to set the image. Typically, this will rely on an icon font. One called Ionicons, which has over 500 icons, comes with the Ionic framework. That's why the use of ion-document-text in Code Segment B just worked. You also have the option of choosing icons for the selected and unselected states with the icon-on and icon-off attributes.

Finally, let's talk about badges. A badge draws attention to something. For instance, it may be a number showing how many unread emails you have. In the Ionic framework, you can use a number or something else. You just set the badge attribute on the ion-tab element. You can set the color by using one of the previously mentioned color classes with the badge-style attribute.

At this point, we've seen how to set up our app's navigation with the ion-tabs element. The content for our app will reside within individual ion-tab elements. With that in mind, let's go deeper into our app and start adding content to our tabs.

Adding Content to a Tab

Content in an ion-tab is added through the ion-content element. This child element serves as a container for the meat of a tab. The ion-content element itself mainly deals with the scrolling behavior. You can customize that behavior with the attributes described here. For our demo, we'll talk about adding basic content. Then, we'll add a list to an ion-content element.

Adding Basic Content

To demonstrate adding basic content to a tab, we'll display the number of items to do. In fact, we'll start in the view (index.html) and replace the Details go here from Code Segment B with the following:

<div class="content padding">
   You have {{items.length}} items outstanding
</div>

Code Segment C

If you open your browser, you'll see something that looks like Figure 3:

Showing the outstanding items.

Figure 3. Showing the outstanding items.

If you look at that figure, you'll notice that the text seems off. The actual count is missing. The code in Code Segment C is trying to bind to the length property of an array named items. Although items does not exist yet, this code did not cause our app to crash or even throw an error. To get our desired behavior, we need to add a controller.

In AngularJS, a controller is a JavaScript constructor function associated with a specific scope. To add a controller, add a new file called controller.js to the www/js directory. Inside of this file, add the code shown in the Code Segment D.

angular.module('todo.controllers', [])
   .controller('IndexCtrl', function($scope) {
      $scope.items = [];
   })
;

Code Segment D

This snippet adds a single controller called IndexCtrl to a module named todo.controllers. If you look at the app, you'll notice that it is not working as desired yet. The reason why is because of two things: first, the module that contains IndexCtrl has not been loaded yet; and second, IndexCtrl has not been bound to the view.

To load the todo.controllers module, there are a couple of things that need to be done. First, the controller code needs to be referenced. To do this, add the line above in the www/index.html file. Then, in www/js/app.js, change the line that says angular.module('starter', ['ionic']) to angular.module('starter', ['ionic', 'todo.controllers']). These two changes will add the todo.controllers module to our app.

To bind IndexCtrl to the view, there is only one change that needs to be made. The change is to alter the line that says to . This change leverages the ngController directive to bind our controller to our view. If you run the app now, you should see the following:

Binding the controller to our view.

Figure 4. Binding the controller to our view.

Although it may not look like much, we're really getting somewhere now. We've gotten some of the app structure put in place. This will allow us to build out the rest of the app fairly quickly. Considering the app is about listing todo items, we will now change our focus to adding a list to a view.

Adding a List

In the Ionic framework, a list is a way of displaying a collection of items. These items are displayed with help from the ion-list and ion-item elements. We'll dive deeper into the capabilities of each of these elements after we update our code. For now, replace the code from Code Segment B that said Tasks go here with the following code:

<ion-list>
   <ion-item ng-repeat="item in items">
      <h2>{{item.title}}</h2>
      <p style="white-space:normal;">{{item.description}}</p>
   </ion-item>
</ion-list>

Code Segment E

If you look at the Items tab in the app now, you will see ... nothing. This is to be expected. This is because the code in Code Segment E uses the ngRepeat directive to render each todo item in ion-list. The items property on our scope (set up in Code Segment D) is empty. We need to create a way for a user to add a todo item to the array of items. In our app, we'll use a dialog.

Adding a Dialog to Your App

The Ionic framework provides a service called $ionicModal to deliver dialogs in your user interface. This service belongs to the ionic module, which is automatically included when you use the Ionic tools to start an app (discussed in the previous article). To add this service, open the www/js/controllers.js file created along with Code Segment D. Then, replace the line that says

.controller('IndexCtrl', function($scope) {

with

.controller('IndexCtrl', function($scope, $ionicModal) {

This injects the $ionicModal service as a dependency to IndexCtrl. This empowers us to initialize, show, and hide dialog windows. To demonstrate how to initialize a dialog window, add the following line below $scope.items = []; from Code Segment D.

$ionicModal.fromTemplateUrl('task-prompt.html', {
   scope: $scope,
   animation: 'slide-in-up'
}).then(function(modal) {
   $scope.modal = modal;
});

Code Segment F

This snippet initializes a dialog. The dialog will share scope with our current view. When opened, the dialog will slide up from the bottom of the screen. The content itself resides in task-prompt.html.

When creating the task-prompt view, there are several options. We could create a new .html file with our content. Alternatively, we can use inline HTML. To use inline HTML, open www/index.htmland add the following code just above the closing tag:

<script id="task-prompt.html" type="text/ng-template">
   <ion-modal-view>
      <ion-header-bar class="bar-calm">
         <h1 class="title">Add New Task</h1>
      </ion-header-bar>
      <ion-content>
         <div class="list">
            <label class="item item-input">
               <input type="text" placeholder="task title" ng-model="newTask.title">
            </label>
            <label class="item item-input">
               <textarea placeholder="task description"
                  ng-model="newTask.description"></textarea>
            </label>
         </div>

         <div class="row">
            <div class="col"><button ng-click="saveTask()"
               class="button button-full
               icon-left ion-checkmark-circled button-balanced">Save Task</button></div>
            <div class="col"><button ng-click="cancelTask()"
               class="button button-full icon-left ion-close-circled button-assertive">
                  Cancel</button></div>
         </div>
      </ion-content>
   </ion-modal-view>
</script>

Code Segment G

This code defines the body of our dialog. To actually open this dialog, we need to make two modifications. We need to update the header of our app. First, let's quickly add some color. Replace the line in www/index.html that says with . This will give the app header some orange . Next, let's add a button to open the dialog we created in Code Segment G.

The Ionic framework lets you add buttons in ion-header-bar. For our needs, add the following code after the h1 element in ion-header-bar.

<button ng-click="showTaskPrompt();"
   class="button button-icon icon ion-plus-round"></button>

Code Segment H

The code in Code Segment H relies on a function called showTaskPrompt to open the dialog created in Code Segment G. We still need to create that function. To do that, open www/js/controllers.js. Add the following code below the code added in Code Segment F.

$scope.showTaskPrompt = function() {
   var newTask = {
      title: '',
      description: '',
      isComplete: null
   };

   $scope.newTask = newTask;
   $scope.modal.show();
};

Code Segment I

This snippet is the heart of the dialog opening. In Code Segment I, we initialize a new task. Then, we show the dialog. The dialog empowers the user to enter the task details. However, it doesn't actually do anything with those details. To get the task back into our list, add the following code underneath the code from Code Segment I.

$scope.saveTask = function() {
   $scope.items.push($scope.newTask);
   $scope.modal.hide();
};

$scope.cancelTask = function() {
   $scope.modal.hide();
};

Code Segment J

After adding the code in Code Segment J, you'll have a fully functioning app. There's a lot more functionality that could be added. Still, this article provided a brief whirlwind example of the Ionic framework in action.

Conclusion

At this point, we've scratched the surface of building an app with Ionic. This article showed how to start a new hybrid app with Ionic. Also, you learned how to run the project in the browser and natively on a device. Some tools and tricks were introduced throughout. To build a feature-rich app, we need to turn our focus to the Ionic framework itself. Good luck! :)



Freelancer Software Developer. Have knowledge in Java, Android, HTML, CSS and Javascript. He has also knowledge in Agile Development

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login