Learning Ionic

4.6 (7 reviews total)
By Arvind Ravulavaru
  • Instant online access to over 8,000+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Ionic – Powered by AngularJS

About this book

With this book, you will learn hybrid mobile application development using Ionic. This book uses Cordova 5.0.0, Ionic CLI 1.5.0, and Ionic 1.0.0 to explain the concepts and build apps.

To begin with, the book helps you understand where Ionic fits in today's world. Then, you will dive deep into Ionic CSS components and Ionic-AngularJS directives and services. You will also examine theming Ionic apps using the built-in SCSS setup.

Next, you will learn to build an Ionic client for a secure REST API, where you will implement user authentication and token-based development. Cordova and ngCordova will be explored, and you will learn how you can integrate device-specific features such as a camera and Geolocation with an Ionic app. We will wrap up the book by building a messaging app, which deals with talking to Firebase (a real-time data store), as well as device features.

By the end of this book, you will be able to develop a hybrid mobile application from start to finish, and generate device-specific installers.

Publication date:
July 2015
Publisher
Packt
Pages
388
ISBN
9781783552603

 

Chapter 1. Ionic – Powered by AngularJS

Ionic is one of the most widely used mobile hybrid frameworks. It has more than 17,000 stars and more than 2,700 forks on GitHub at the time of writing this chapter. Ionic is built on top of AngularJS, a super heroic framework for building MVW apps. In this introductory chapter, we will take a look at AngularJS and understand how it powers Ionic. We will take a look at a couple of key AngularJS components, named directives, and services that are widely used when working with Ionic.

Note

This book assumes that you have basic to intermediate knowledge of AngularJS. If not, you can follow the book AngularJS Essentials, Rodrigo Branas, or the video Learning AngularJS, Jack Herrington, both by Packt Publishing, to get yourself acquainted with AngularJS.

In this chapter, I will explain only AngularJS directives and services. For other core AngularJS concepts, refer to the book/video mentioned earlier.

In this chapter, we will cover the following topics:

  • What is separation of concerns?

  • How does AngularJS solve this problem?

  • What are AngularJS built-in directives and custom directives?

  • What are AngularJS services and how do custom services work?

  • How are directives and services leveraged in Ionic?

 

Understanding the separation of concerns


Server-side web applications have been around for quite some time now. However, the Web is evolving at such a fast pace that we are driving applications from the client-side rather than the server-side. Gone are those days when the server dictates to the client about what activities to perform and what user interface to display.

With the extensive growth of asynchronous and highly interactive web pages, the user experience can be made better with client-side driven applications than server-side driven applications. As you already know, libraries such as jQuery and Zepto help us in achieving this quite easily.

Let's take a typical use case where a user enters data in a textbox and clicks on a Submit button. This data is then posted to the server via AJAX, and the response is rendered in the UI without any page refresh.

If we had to replicate this using jQuery (with a pseudo syntax), it would look something like this:

// Assuming that jQuery is loaded and we have a textbox, a button and a container to display the results

var textBox = $('#textbox');
var subBtn = $('#submitBtn');

subBtn.on('click', function(e) {
  e.preventDefault();
  var value = textbox.val().trim();
  if (!value) {
    alert('Please enter a value');
   return;
  }

  // Make an AJAX call to get the data
  var html2Render = '';

  $.post('/getResults', {
      query: value
    })
    .done(function(data) {
      // process the results 
      var results = data.results;
      for (var i = 0; i < results.length; i++) {
        // Get each result and build a markup
        var res = results[i];
        html2Render += ' < div class = "result" > ';
        html2Render += ' < h2 > ' + res.heading + ' < /h2>';
        html2Render += ' < span > ' + res.summary + ' < /span>';
        html2Render += ' < a href = "' + res.link + '" > ' + res.linkText + ' < /a>';
        html2Render += ' < /div>'
      }
      // Append the results HTML to the results container
      $('#resultsContainer').html(html2Render);
    });

});

Note

The preceding code is not for execution. It is just an example for reference.

When you click on the button, the textbox value is posted to the server. Then, an HTML markup is generated with results (JSON object) from the server and injected into the results container.

But, how maintainable is the preceding code?

How can you test individual pieces? For example, we want to test whether the validations work fine or whether the response is coming correctly.

Let's assume that we want to make modifications (such as adding a favicon of the resultant web page next to each search result as an inline icon) to the results template that we are building on the fly. How easy would it be to introduce this change in the preceding code?

This is a concern with separations. These separations are between validations, making AJAX requests and building markups. The concern is that they are tightly coupled with each other, and if one breaks, all would break and none of the preceding code can be reused.

If we were to separate the preceding code into various components, we would end up with a Model View Controller (MVC) architecture. In a typical MVC architecture, a model is an entity where you save the data, and a controller is where you massage the data before you display it on a view.

Unlike the server-side MVC, the client-side MVC has an extra component named the router. A router is typically a URL of the web page that dictates which model/view/controller should be loaded.

This is the basic idea behind AngularJS, and how it achieves separation of concerns and at the same time provides a single-page application architecture.

Referring to the preceding example, the server interaction layer (AJAX) would be separated from the main code and will interact with a controller on an on-demand basis.

Knowing this, we will now take a quick look at few key AngularJS components.

 

AngularJS components


AngularJS is driven from HTML, unlike most client-side JavaScript frameworks. In a typical web page, AngularJS takes care of wiring key pieces of code for you. So, if you add a bunch of AngularJS directives to your HTML page and include the AngularJS source file, you could easily build a simple app without writing a single line of JavaScript code.

To illustrate the preceding statement, we can build a login form with validations, without writing a single line of JavaScript.

It would look something like this:

<html ng-app="">
<head>
   <script src="angular.min.js" type="text/JavaScript"></script>
</head>
<body>
   <h1>Login Form</h1>
   <form name="form" method="POST" action="/authenticate">
         <label>Email Address</label>
         <input type="email" name="email" ng-model="email" required> 
 

         <label>Password</label>
         <input type="password" name="password" ng-model="password" required> 

         <input type="submit" ng-disabled="!email || !password" value="Login">
   </form>
</body>
</html>

In the preceding code snippet, the attributes that start with ng- are called as AngularJS directives.

Here, the ng-disabled directive takes care of adding the disabled attribute to the Submit button when the e-mail or password is not valid.

Also, it is safe to say that the scope of the directive is limited to the element and its children on which the directive is declared. This solves another key issue with the JavaScript language where, if a variable were not declared properly, it would end up in the Global Object, that is, the Window Object.

Note

If you are new to scope, I recommend that you go through https://docs.angularJS.org/guide/scope. Without proper knowledge of scope and root scope, this book would be very difficult to follow.

Now, we will go to the next component of AngularJS named Dependency Injection (DI). DI takes care of injecting units of code where required. It is one of the key enablers that help us achieve separation of concerns.

You can inject various AngularJS components, as you require. For instance, you can inject a service in a controller.

Note

DI is another core component of AngularJS that you need to be aware of. You can find more information at https://docs.angularJS.org/guide/di.

To understand services and controllers, we need to take a step back. In a typical client-side MVC framework, we know that the model stores the data, the view displays the data, and the controller massages the data present in the model before it gets displayed to the view.

In AngularJS, you can relate with the preceding line as follows:

  • HTML—Views

  • AngularJS controllers—Controllers

  • Scope objects—Model

In AngularJS, HTML acts as the templating medium. An AngularJS controller would take the data from scope objects or the response from a service and then fuse them to form the final view that gets displayed on the web page. This is analogous to the task we did in the search example where we iterated over the results, built the HTML string, and then injected the HTML into the DOM.

Here, as you can see, we are separating the functionality into different components.

To reiterate, the HTML page acts as a template, and the factory component is responsible for making an AJAX request. Finally, the controller takes care of passing on the response from factory to the view, where the actual UI is generated.

The AngularJS version of the search engine example would be as shown here.

The index.html or the main page of the app would look like this:

<html ng-app="searchApp">
<head>
   <script src="angular.min.js" type="text/JavaScript">
   <script src="app.js" type="text/JavaScript">
</head>
<body ng-controller="AppCtrl">
   <h1>Search Page</h1>
   <form>
         <label>Search : </label>
          <input type="text" name="query" ng-model="query" required> 
          <input type="button" ng-disabled="!query" value="Search" ng-click="search()">
   </form>

   <div ng-repeat="res in results">
         <h2>{{res.heading}}</h2>
         <span>{{res.summary}}</span>
         <a ng-href="{{res.link}}">{{res.linkText}}</a>
   </div>

</body>
</html>

The app.js would look like this:

var searchApp = angular.module('searchApp', []);

searchApp.factory('ResultsFactory', ['$http', function($http) {

return {
 
   getResults : function(query){
         return $http.post('/getResults', query);
       }

};


}]);


searchApp.controller('AppCtrl', ['$scope','ResultsFactory',function($scope, ResultsFactory) {

   $scope.query = '';
   $scope.results = [];

   $scope.search = function(){
          var q = {
              query : $scope.query
             };
          ResultsFactory.getResults(q)
                .then(function(response){

                 $scope.results = response.data.results;
                    
                 });
       }


}]);

Note

In AngularJS, the factory component and the service component are interchangeably used. If you would like to know more about them, refer to the discussion on stack overflow at http://stackoverflow.com/questions/15666048/service-vs-provider-vs-factory.

The index.html file consists of the HTML template. This template is hidden by default when the page is loaded. When the results array is populated with data, the markup is generated from the template using the ng-repeat directive.

In app.js, we started off by creating a new AngularJS module with the name as searchApp. Then, we created a factory named ResultsFactory, whose sole purpose is to make an AJAX call and return a promise. Finally, we created the controller, named AppCtrl, to coordinate with the factory and update the view.

The search function declared on the button's ng-click directive is set up in the AppCtrl. This button would only be enabled if valid data is entered in the search box. When the Search button is clicked, the listener registered in the controller is invoked. Here, we will build the query object needed for the server to process and call getResults method in ResultsFactory. The getResults method returns a promise, which gets resolved when the response from the server is back. Assuming a success scenario, we will set $scope.results to the search results from the server.

This modification to the $scope object triggers an update on all instances of the results array. This, in turn, triggers the ng-repeat directive on the HTML template, which parses the new results array and generates the markup. And voila! The UI is updated with the search results.

Tip

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you. For this chapter, you can chat with the author and clear your queries at GitHub (https://github.com/learning-ionic/Chapter-1).

The preceding example shows how you can structure your code in an orderly fashion that can be maintainable and testable. Now, adding an extra image next to each search result is very easy, and any developer with basic knowledge of the Web can update the application.

 

AngularJS directives


Quoting from the AngularJS documentation.

"At a high level, directives are markers on a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS's HTML compiler ($compile) to attach a specified behavior to that DOM element or even transform the DOM element and its children."

This is a very useful feature when you want to abstract out the common functionality on your web page. This is similar to what AngularJS has done with its directives, such as the following ones:

  • ng-app: This initializes a new default AngularJS module when no value is passed to it; otherwise, it initializes the named module

  • ng-model: This maps the input element's value to the current scope

  • ng-show: This shows the DOM element when the expression passed to ng-show is true

  • ng-hide: This hides the DOM element when the expression passed to ng-hide is true

  • ng-repeat: This iterates the current tag and all its children based on the expression passed to ng-repeat

Referring to the Search App, which we built earlier, imagine that there are multiple pages in your web application that need this search form. The expected end result is pretty much the same across all pages.

So, instead of replicating the controller and the HTML template where needed, we would abstract this functionality into a custom directive.

You can initialize a new directive on a DOM element by referring to it using an attribute notation, such as <div my-search></div>, or you can create your own tag/element, such as <my-search></my-search>.

This would enable us to write the search functionality only once but use it many times. AngularJS takes care of initializing the directive when it comes into view and destroying the directive when it goes away from the view. Pretty nifty, right?

We will update our Search App by creating a new custom directive called my-search. The sole functionality of this directive would be to render a textbox and a button. When the user clicks on the Search button, we will fetch the results and display them below the search form.

So, let's get started.

As with any AngularJS component, the directives are also bound to a module. In our case, we already have a searchApp module. We will bind a new directive to this module:

searchApp.directive('mySearch', [function () {
   return {
          template : 'This is Search template',
          restrict: 'E',
          link: function (scope, iElement, iAttrs) {

          }
   };
}]);

The directive is named mySearch in camel case. AngularJS will take care of matching this directive with my-search when used in HTML. We will set a sample text to the template property. We will restrict the directive to be used as an element (E).

Note

Other values that you can restrict in an AngularJS directive are A (attribute), C (class), and M (comment). You can also allow the directive to use all four (ACEM) formats.

We have created a link method. This method is invoked whenever the directive comes into view. This method has three arguments injected to it, which are as follows:

  • scope: This refers to the scope in which this tag prevails in the DOM. For example, it could be inside AppCtrl or even directly inside rootScope (ng-app).

  • iElement: This is the DOM node object of the element on which the directive is present.

  • iAttrs: These are the attributes present on the current element.

In our directive, we would not be using iAttrs, as we do not have any attributes on our my-search tag.

In complex directives, it is a best practice to abstract your directive template to another file and then refer it in the directive using the templateUrl property. We will do the same in our directive too.

You can create a new file named directive.html in the same folder as index.html and add the following content:

<form>
    <label>Search : </label>
    <input type="text" name="query" ng-model="query" required>
    <input type="button" ng-disabled="!query" value="Search" ng-click="search()">
</form>

<div ng-repeat="res in results">
    <h2>{{res.heading}}</h2>
    <span>{{res.summary}}</span>
    <a ng-href="{{res.link}}">{{res.linkText}}</a>
</div>

In simple terms, we have removed all the markup in the index.html related to the search and placed it here.

Now, we will register a listener for the click event on the button inside the directive. The updated directive will look like this:

searchApp.directive('mySearch', [function() {
        return {
            templateUrl: './directive.html',
            restrict: 'E',
            link: function postLink(scope, iElement, iAttrs) {
                scope.search = function() {
                      var q = {
                          query : scope.query
                      };

                    // Interact with the factory (next step)
                }
            }
        };
    }])

As you can see from the preceding lines of code, the scope.search method is executed when the click event on the button is fired and scope.query returns the value of the textbox. This is quite similar to what we did in the controller.

Now, when a user clicks on the Search button after entering some text, we will call getResults method from ResultsFactory. Then, once the results are back, we will bind them to the results property on scope.

The completed directive will look like this:

searchApp.directive('mySearch', ['ResultsFactory', function(ResultsFactory) {
        return {
            templateUrl: './directive.html',
            restrict: 'E',
            link: function postLink(scope, iElement, iAttrs) {
                scope.search = function() {
                      var q = {
                          query : scope.query
                      };

                    ResultsFactory.getResults(q).then(function(response){
                      scope.results = response.data.results;
                    });
                }
            }
        };
    }])

With this, we can update our index.html to this:

<html ng-app="searchApp">
<head>
   <script src="angular.min.js" type="text/JavaScript"></script>
   <script src="app.js" type="text/JavaScript"></script>
</head>
<body>
   <my-search></my-search>
</body>
</html>

We can update our app.js to this:

var searchApp = angular.module('searchApp', []);

searchApp.factory('ResultsFactory', ['$http', function($http){

return {
 
   getResults : function(query){
         return $http.post('/getResults', query);
       }

};


}]);


searchApp.directive('mySearch', ['ResultsFactory', function(ResultsFactory) {
        return {
            templateUrl: './directive.html',
            restrict: 'E',
            link: function postLink(scope, iElement, iAttrs) {
                scope.search = function() {
                      var q = {
                          query : scope.query
                      };

                    ResultsFactory.getResults(q).then(function(response){
                      scope.results = response.data.results;
                    });
                }
            }
        };
    }]);

Quite simple, yet powerful!

Now, you can start sprinkling the <my-search></my-search> tag wherever you need a search bar.

You can take this directive to another level, where you can pass in an attribute named results-target to it. This would essentially be an ID of an element on the page. So, instead of showing the results below the search bar always, you can show the results inside the target provided.

Note

AngularJS comes with a lightweight version of jQuery named jqLite. jqLite does not support selector lookup. You need to add jQuery before AngularJS for AngularJS to use jQuery instead of jqLite. You can read more about jqLite at https://docs.angularJS.org/api/ng/function/angular.element.

This very feature makes AngularJS directives a perfect solution for reusable components when dealing with DOM.

So, if you want to add a new navigation bar to your Ionic app, all you need to do is throw in an ion-nav-bar tag, such as the following one, one your page:

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

Then, things will fall in place.

We went through the pain of understanding a custom directive so that you could easily relate to Ionic components that are built using AngularJS directives.

 

AngularJS services


AngularJS services are substitutable objects that can be injected into directives and controllers via Dependency Injection. These objects consist of simple pieces of business logic that can be used across the app.

AngularJS services are lazily initialized only when a component depends on them. Also, all services are singletons, that is, they get initialized once per app. This makes services perfect for sharing data between controllers and keeping them in memory if needed.

The $interval is another service that is available in AngularJS. The $interval is the same as setTimeInterval(). It wraps setTimeInterval() and returns a promise when you register this service. This promise then can be used to destroy $interval later on.

Another simple service is $log. This service logs messages to the browser console. A quick example of this would be as follows:

myApp.controller('logCtrl', ['$log', function($log) {
        
    $log.log('Log Ctrl Initialized');
        
    }]);

So, you can see the power of services and understand how simple pieces of business logic can be made reusable across the app.

You can write your own custom services that can be reused across the app. Let's say that you are building a calculator. Here, methods such as add, subtract, multiply, divide, square, and so on, can be part of the service.

Coming back to our Search App, we used a factory that is responsible for server-side communications. Now, we will add our own service.

Note

Service and factory components can be used interchangeably. Refer to http://stackoverflow.com/questions/15666048/service-vs-provider-vs-factory for more information.

For instance, when the user searches for a given keyword(s) and posts displaying the results, we would like to save the results in the local storage. This will ensure that, next time, if the user searches with the same keyword(s), we will display the same results rather than making another AJAX call (like in offline mode).

So, this is how we will design our service. Our service will have the following three methods:

  • isLocalStorageAvailable(): This method checks whether the current browser supports any storage API

  • saveSearchResult(keyword, searchResult): This method saves a keyword and search result in the local storage

  • isResultPresent(keyword): This method retrieves the search result for a given keyword

Our service will look as follows:

searchApp.service('LocalStorageAPI', [function() {
    this.isLocalStorageAvailable = function() {
         return (typeof(localStorage) !== "undefined");
    };

    this.saveSearchResult = function(keyword, searchResult) {
        return localStorage.setItem(keyword, JSON.stringify(searchResult));
    };

    this.isResultPresent = function(keyword) {
        return JSON.parse(localStorage.getItem(keyword));
    };
}]);

Note

Local storage cannot store an object. Hence, we are stringifying the object before saving and parsing the object after retrieving it.

Now, our directive will use this service while processing the search. The updated mySearch directive will look like this:

searchApp.directive('mySearch', ['ResultsFactory', 'LocalStorageAPI', function(ResultsFactory, LocalStorageAPI) {
        return {
            templateUrl: './directive.html',
            restrict: 'E',
            link: function postLink(scope, iElement, iAttrs) {

                var lsAvailable = LocalStorageAPI.isLocalStorageAvailable();
                scope.search = function() {
                    if (lsAvailable) {
                        var results = LocalStorageAPI.isResultPresent(scope.query);
                        if (results) {
                            scope.results = results;
                            return;
                        }
                    }
                    var q = {
                        query: scope.query
                    };

                    ResultsFactory.getResults(q).then(function(response) {
                        scope.results = response.data.results;
                        if (lsAvailable) {
                        LocalStorageAPI.saveSearchResult(scope.query, data.data.results);
                        }
                    });
                }
            }
        };
    }]);

As mentioned earlier, we will check whether local storage is available and then save and fetch the results using the LocalStorageAPI service.

Similarly, Ionic also provides custom services that we are going to consume. We will take a look at them in detail in Chapter 5, Ionic Directives and Services.

An example of an Ionic service would be the loading service. This service shows a loading bar with the text you have provided. It looks something like this:

$ionicLoading.show({
  template: 'Loading...'
});

Then, you will see an overlay that is generally used to indicate background activity and block the user from interaction.

 

AngularJS resources


I would like to point out a few GitHub repositories that consist of valuable AngularJS resources. You can refer to these repositories to know what is the greatest and latest in the AngularJS world. Some of the repositories are as follows:

 

Summary


In this chapter, we saw what separation of concerns is and how AngularJS is designed to solve this problem. We quickly went through some of the key AngularJS components that we would use while working with Ionic. You also saw how to create custom directives and custom services, and learned about their usage. The rule of thumb while creating reusable pieces of code when working with AngularJS is to use directives when dealing with HTML elements (DOM), and services/factories otherwise.

You also understood that Ionic uses these AngularJS components to expose an easy-to-use API while building mobile hybrid apps.

In the next chapter, you will be introduced to Ionic. You will learn how to set it up, scaffold a basic app, and understand the project structure. You will also take a look at the bigger picture of developing a mobile hybrid application.

About the Author

  • Arvind Ravulavaru

    Arvind Ravulavaru is a platform architect at Ubiconn IoT Solutions, with over 9 years of experience in software development and 2 years in hardware & product development. For the last 5 years, he has been working extensively on JavaScript, both on the server side and the client side. And for the last couple of years in IoT, building a platform for rapidly developing IoT solutions, named The IoT Suitcase. Prior to that, Arvind worked on big data, cloud computing, and orchestration.

    Browse publications by this author

Latest Reviews

(7 reviews total)
Libro escencial para aquel que quiere aprender Ionic v1
A little outdtaed but all books are...
Gutes Buch, Lerneinstieg in IONIC sehr Intuitiv...
Book Title
Unlock this full book with a FREE 10-day trial
Start Free Trial