Click here to Skip to main content
15,881,882 members
Articles / Hosted Services / PhoneGap

Developing Hybrid Mobile Apps with Phonegap, AngularJS, Bootstrap

Rate me:
Please Sign up or sign in to vote.
4.29/5 (15 votes)
1 Apr 2015CPOL8 min read 81.5K   33   7
How to develop Hybrid Mobile Apps with Phonegap, AngularJS, Bootstrap

In my post, Develop mobile applications using web development skills, I pointed out a list of possible frameworks which can be used to create a hybrid mobile app. My favorite choice so far is using Cordova/Phonegap (Read my post on my opinion about Cordova/Phonegap) in combination with a hybrid app development framework. In my previous mobile applications I have developed, I used to use jQuery mobile as my framework of choice for developing the UI of my apps. Nowadays, I have switched to another combination, which is:

Cordova/Phonegap + AngularJS + Bootstrap

The hybrid mobile app architecture with Phonegap, AngularJS, Bootstrap looks like this:

Image 1

The presentation layer is built with Bootstrap framework, the app domain is modeled using AngularJS, and is packaged using Cordova/Phonegap to a native app. Let us go through the components of this hybrid mobile app architecture and describe them.

Bootstrap

Bootstrap is a mobile-first responsive front-end framework. What does this mean? Bootstrap has an easy to use responsive grid which allows you to position your layout in a well structured responsive way. As the framework is built with mobile use in mind, it responds well to different screen sizes and adapts the layout of the app easily to different screen sizes. This is a good possibility to use the very same implementation for tablet and mobile devices of different screen sizes. And it is not only the grid that makes it special. It helps you manage typography, responsive images, forms, form validation messages, notification messages, responsive tables, and a good number of UI components. You can download it from getbootstrap.com.

AngularJS

AngularJS

AngularJS

A very powerful, full-featured JavaScript MVW framework. With AngularJS framework, you can give a structure to your app domain model and manage your app logic in a very flexible way. Everything is organized around a model which is displayed through a View. Views can be well structured templated HTML code styled and organized using Bootstrap. Controllers organize the communication between the View, Services, and all other parts. The framework supports a good routing mechanism, which can also be extended by other extension libraries for more powerful functionalities. There are a plethora of extension libraries for AngularJS which add value to the framework by filling in the gaps of the framework. You can get AngularJS from angularjs.org.

Cordova/Phonegap

Cordova is an Apache project which creates an underlying platform for developing multiplatform mobile applications. In our case, it makes possible the AngularJS+Bootstrap web app to be packaged to a native mobile app which can be published to the mobile markets and be installed in mobile devices. Adobe PhoneGap is a distribution of Cordova.

Basically what Cordova does is to make possible the web app to run inside a WebView component of a native app, we can say it as a native package of a web app. You can do the packaging using Cordova Command Line Interface (CLI) or using Adobe PhoneGap Build which does not require any installations.

The most powerful feature of Cordova in my opinion is the extension possibility by plugins. By installing specific plugins, you get access to device’s hardware such as camera, compass, geolocation, as well as other device specific APIs such as contacts, media, notifications, etc. Very powerful plugins such as barcode reading, push notifications, and many more, can give your application good features by writing few lines of code.

The Development Process

As we described the architecture parts, let us start with the process of developing hybrid mobile apps with Phonegap, AngularJS, Bootstrap. We start with creating a sample application which shows you your current location coordinates and demonstrates the development process. The easiest way to start the app development is by creating initial template using Cordova/Phonegap CLI. We do this through this command (if you do not have cordova cli installed, here is the link showing how to do it: https://cordova.apache.org/docs/en/4.0.0/guide_cli_index.md.html).

phonegap create blogSample com.ariancelina.blogSample BlogSample

The create command requires 3 arguments:

  1. The directory name to be created for generation of the project, in our case “blogSample
  2. The second argument is the project identifier, in our case “com.ariancelina.blogSample”. Usually, it is used as a reversed domain name identifier
  3. The third argument is the display title of the application, in our case “BlogSample

In this sample code, I used phonegap to create the app. The command equally applies to cordova as well.

If you already had phonegap installed and the app was created successfully, inside blogSample directory you should have a config.xml file and four other directories (hooks, platforms, plugins, and www). Platforms folder contains builds for specific platforms, plugins directory contains installed plugins, and WWW directory contains all our web code (AngularJS + Bootstrap + other files).

To read our location coordinates, we need to install the Geolocation plugin (Find the list of plugins) and we do that by executing this command:

cordova plugin add org.apache.cordova.geolocation

Now that we have the initial structure, we need to add platforms to which we want to deploy, but to do that, we need to be inside our app directory, which in our case is blogSample. Adding ios platform is done using the command:

phonegap platform add ios

After the platform is added, we can build our app using:

phonegap build ios

We can repeat the last two commands for all other supported platforms like Android, Windows Phone, etc.

If we want to test our app, we can go to directory blogSample/platforms/ios and launch BlogSample.xcodeproj and run the app in simulator or existing device.

We have our platform set up, now let us add the AngularJS and Bootstrap files. After we download these (download AngularJS as a zip file so you get all parts of it), we put inside blogSample/www/js directory AngularJS and Bootstrap js files: jquery-1.11.2.min.js (jquery is a dependency of bootstrap and can be downloaded from jquery.com), angular.min.js, angular-route.min.js and bootstrap.min.js. Inside blogSample/www/css directory, we put bootstrap.min.css and bootstrap-theme.min.css files. And the last part here is to link these files in our main file index.html. We put CSS code in head section:

HTML
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"/>
        <link rel="stylesheet" type="text/css" href="css/bootstrap-theme.min.css"/>
        <link rel="stylesheet" type="text/css" href="css/index.css" />

and near the closing body tag, we link the JavaScript files.

HTML
<script type="text/javascript" src="js/jquery-1.11.2.min.js"></script>
        <script type="text/javascript" src="js/bootstrap.min.js"></script>
        <script type="text/javascript" src="cordova.js"></script>
        <script type="text/javascript" src="js/angular.min.js"></script>
        <script type="text/javascript" src="js/angular-route.min.js"></script>
        <script type="text/javascript" src="js/index.js"></script>

Now we have the setup ready and we can start coding the logic. We need three things to define to make it work, we need an angular route config which allows us to navigate from page to page, then we need an angular controller, and a view which will display the user his/her current location.

We start with the app.js file which contains the initialization of the js app. This file also is the place where the initialization events are placed. In our case, it looks like this:

JavaScript
var blogSample = angular.module('blogSample', ['ngRoute','ui.bootstrap']);
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
            document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
        navigator.geolocation.getCurrentPosition(app.onSuccess, app.onErr);
    },
    onErr: function(error)
    {
        alert('Unable to get your location. 
	Without location you will not be able to use navigate feature! Error:' + '\n' + error.message);
    },

    onSuccess: function(position)
    {
        blogSample.latitude = position.coords.latitude;
        blogSample.longitude = position.coords.longitude;
    }
};

We start by defining our angular app, blogSample (line 1). We initiate it and define the modules which we need (ngRoute, ui.bootstrap). There are other interesting things happening here. As we are used to use jquery ready function to react when the page is loaded and ready for use, here we have onDeviceReady event which is fired when the app is loaded and we can start using it. Inside this event, we will get the current position of the device through this line of code:

JavaScript
navigator.geolocation.getCurrentPosition(app.onSuccess, app.onErr);

The getCurrentPosition function which gets the current latitude and longitude of the device, needs two functions as parameters, first being the function that is called if the current location can be obtained successfully, and the latter for errors. The error function is used to report the unavailability of the location. The success function is used to read the coordinates and bind them to our angular app, blogSample through this function:

JavaScript
onSuccess: function(position)
{
   blogSample.latitude = position.coords.latitude;
   blogSample.longitude = position.coords.longitude;
}

Now that we have our app setup ready, let us define two views, one about page and the other showing location information. Showing the coordinates inside the view is done using:

HTML
<p class="text-center"> Your location is: <br/>
  Latitude: {{latitude}}<br/>
  Longitude: {{longitude}} <br/>
</p>

AngularJS will substitute the values inside curly braces with current coordinates set in onSuccess function. But views do not access application level values. We usually link a controller with a view, and view is limited to the scope of that controller, so we need to define a controller to glue the coordinates to the view. The controller will look like:

JavaScript
blogSample.controller('mainController', function($scope, $route){
    $scope.latitude = blogSample.latitude;
    $scope.longitude = blogSample.longitude;          
});

and finally we add the router configuration to bind the controller to the view and enable the user moving between pages. The router has this code:

JavaScript
blogSample.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/', {
        templateUrl: 'views/main.html',
        controller: 'mainController'
      }).
      when('/about', {
        templateUrl: 'views/about.html'
      }).
      otherwise({
        redirectTo: '/'
      });
  }]);

The router part defines one default url and ‘/abouturl. The default url/’ binds to main.html view, and the ‘/abouturl binds to about.html view.

Now that we have all the building pieces in place, we need to add the reference of last created files in index.html and the references will look like this:

HTML
<script type="text/javascript" src="cordova.js"></script>

        <script type="text/javascript" src="js/libs/jquery-1.11.2.min.js"></script>
        <script type="text/javascript" src="js/libs/bootstrap.min.js"></script>
        <script type="text/javascript" src="js/libs/angular.min.js"></script>
        <script type="text/javascript" src="js/libs/angular-route.min.js"></script>
        <script type="text/javascript" src="js/libs/ui-bootstrap-tpls-0.11.0.min.js"></script>
        <script type="text/javascript" src="js/app.js"></script>
        <script type="text/javascript" src="js/angular/routes.js"></script>
        <script type="text/javascript" src="js/angular/controller.js"></script>
   

        <script type="text/javascript">
            app.initialize();
        </script>

Now that everything is on place, we can deploy our app to the phone for testing, or run it in a simulator. Running the application is different depending on the platform. You may use the simulators that can be started from phonegap, by xcode, eclipse, or Android studio, but for any serious app development, I would strongly suggest you try your app in a real device. I will not go into details about deployment as it is out of scope of this post, but in the simplest scenario, you may go to platforms folder inside your phonegap project folder, and open the project of the specific platform and run the project from the respective IDE.

The complete source code of this application can be found on GitHub https://github.com/acelina/phonegapWithAngularJs, you may download it and try it on your computer.

The post Developing hybrid mobile apps with Phonegap, AngularJS, Bootstrap appeared first on arian-celina.com.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
Albania Albania
I am a Software Architect, a web developer, and a Computer Science lecturer. I enjoy solving business problems by providing software solutions to them. My favorite technologies and fields of interest include ASP.NET, C# programming language, Java programming language, Javascript, jQuery, AngularJS, Web Services, REST, and mobile application development

Comments and Discussions

 
GeneralMy vote of 5 Pin
Anele 'Mashy' Mbanga9-Apr-15 4:13
professionalAnele 'Mashy' Mbanga9-Apr-15 4:13 
GeneralRe: My vote of 5 Pin
Arian Celina17-Apr-15 0:11
Arian Celina17-Apr-15 0:11 
QuestionIonic Framework Pin
CatalinTomescuUS3-Apr-15 6:24
CatalinTomescuUS3-Apr-15 6:24 
AnswerRe: Ionic Framework Pin
Arian Celina4-Apr-15 1:53
Arian Celina4-Apr-15 1:53 
AnswerRe: Ionic Framework Pin
Jenny B Jones10-Apr-15 23:14
professionalJenny B Jones10-Apr-15 23:14 
QuestionBootstrap is best Pin
Member 115758152-Apr-15 1:59
Member 115758152-Apr-15 1:59 
AnswerRe: Bootstrap is best Pin
Arian Celina2-Apr-15 2:11
Arian Celina2-Apr-15 2:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.