Mobile Apps

Mobile apps are not the next frontier for software developers – they’re already here. There are already 1.2 billion mobile web app users, and that number is growing rapidly (Wikipedia). Soon, the number of mobile devices will exceed the number of people on the planet. At the rate at which the number of mobile devices is growing, it’s estimated that 5.1 billion people will be using mobile phones by 2017.

For us as app developers, it’s important that we develop for mobile technology if we want to stay relevant. With AngularJS, we have some great support for mobile, written by both the Angular team and the community.

In this section, we’re going to work through these two different ways to give our users a mobile experience for our app:

Responsive Web Apps

The easiest way to support mobile with Angular is by using the tools we already know and love – HTML and CSS– to create a mobile-ready Angular app. Since Angular apps are already based on HTML, making our designs and interaction responsive is only a matter of building the architecture that will support different devices.

Interaction

For the desktop, the ability to create interactions is already available to us through the ng-click and family directives.

Beginning with Angular version 1.2.0, we now have the ability to use touch events using the new ngTouch module. Since ngTouch is not built into the core Angular library, we need to install it.

Installation

We can install ngTouch in any of several ways. The simplest way to install the ngTouch module is by downloading the source from angularjs.org.

Find the extras in the download section, then we can download and store the ng-touch.js file into an accessible location in our app.

Alternatively, we can use Bower to install angular-touch:

$ bower install angular-touch --save

Either way, we need to reference the library in our index.html as a script:

<script src="/bower_components/angular-touch/angular-touch.js"></script>

Finally, we need to include ngTouch as a dependency in our app:

angular.module('myApp', ['ngTouch']);

Now we’re ready to take advantage of the ngTouch library.

ngTouch

Mobile browsers work slightly differently than desktop browsers when dealing with click events. Mobile browsers detect a tap event then wait about 300 ms to detect any other taps (i.e., they wait to find out if we’re double-tapping the device). After this delay, the browser fires a click event.

This delay can make our apps feel incredibly unresponsive. Instead of dealing with the click event, we can detect touch events instead.

The ngTouch library seamlessly handles this functionality for us through the ng-click directive and takes care of calling the correct click event for us. This so-called fast click event will be called.

After the fast click has been called, the browser’s delayed click is called secondarily, causing a ‘double’ action. ngTouch takes care of removing this browser delay on ng-click events.

Using the ngClick directive on mobile devices works the exact same way on mobile browsers as it does on desktop browsers:

<button ng-click="save()">Save</button>

ngTouch also introduces two new directives: swipe directives. These swipe directives allow us to capture user swipes, either left or right across the screen. These are useful for situations where we want the user to be able to swipe through a photo gallery photo or to a new portion of our app.

The ngSwipeLeft directive detects when an element is swiped from the right to the left, while the ngSwipeRight directive detects when an element is swiped from the left to the right.

One of the nice features the ngSwipe* directives give us is that they work both with touch-based devices as well as with mouse clicking and dragging.

Using the ngSwipe* directives is easy. For instance, let’s say we have a list of emails and we want to reveal actions for each email, like the popular mobile email client MailboxApp.

We can easily implement that functionality using these swipe directives on our list of elements. When we are showing our list of emails, we enable swiping in one direction to show the actions we can take on that particular mail item.

When we are showing actions for the mail item, we enabled swiping in the other direction to hide the actions we can take.

<ul>
  <li ng-repeat="mail in emails">
    <div 
      ng-show="!mail.showActions"
      ng-swipe-left="mail.showActions=true">
      <div class="from">
        From: <span>{{ mail.from }}</span>
      </div>
      <div class="body">
        {{ mail.body }}
      </div>
    </div>
    <div
      ng-show="mail.showActions"
      ng-swipe-right="mail.showActions=false">
      <ul class="actions">
        <li><button>Archive</button></li>
        <li><button>Trash</button></li>
      </ul>
    </div>
  </li>
</ul>

logo

$swipe Service

For more custom touch-based animations, we can use the $swipe service directly. The $swipe service is a service that abstracts the details of hold-and-drag swiping behavior.

The $swipe service has a single method called bind(). This bind() method takes an element to which it binds the swipe actions as well as an object with four event handlers.

These event handlers are called with an object that contains the coordinates object, like so: { x: 200, y: 300 }.

The four events handlers handle the following events:

The start event is fired on either a mousedown or a touchstart event. After this event, the $swipe service sets up watches for touchmove and mousemove events. These events are only fired until the total distance moved exceeds a small distance (to prevent accidental swipes).

Once this distance has been surpassed, one of two events happens:

The move event is called on mousemove and touchmove events only after the $swipe service has determined that a swipe is, in fact, in progress.

The end event is fired when the touchend or a mouseup event has finished and after the move event has been fired.

The cancel event is called on either a touchcancel or when we begin scrolling after the start event instead.

For instance, we can create a directive that enables swiping between slides that might control a projector screen. To handle swiping on the mobile control, we use the $swipe service to handle our custom logic for how to display the UI layer.

angular.module('myApp')
.directive('mySlideController', ['$swipe',
  function($swipe) {
      return {
      restrict: 'EA',
      link: function(scope, ele, attrs, ctrl) {
        var startX, pointX;

        $swipe.bind(ele, {
          'start': function(coords) {
            startX = coords.x;
            pointX = coords.y;
          },
          'move': function(coords) {
            var delta = coords.x - pointX;
            // ...
          },
          'end': function(coords) {
            // ...
          },
          'cancel': function(coords) {
            // ...
          }
        });
      }
    }
}]);

angular-gestures and Multi-Touch Gestures

angular-gestures is an Angular module that gives us the ability to handle multi-touch actions in our Angular apps. It is based on the very popular and well-tested Hammer.js library.

The Hammer.js library gives us a bunch of events common to touchscreen events:

The angular-gestures library enables us to use these events using Angular directives. For instance, all of the following directives are available to us:

 
This page is a preview of ng-book.
Get the rest of this chapter plus 600 pages of the best Angular content on the web.

 

Ready to master AngularJS?

  • What if you could master the entire framework – with solid foundations – in less time without beating your head against a wall? Imagine how quickly you could work if you knew the best practices and the best tools?
  • Stop wasting your time searching and have everything you need to be productive in one, well-organized place, with complete examples to get your project up without needing to resort to endless hours of research.
  • You will learn what you need to know to work professionally with ng-book: The Complete Book on AngularJS or get your money back.
Get it now