Building Hybrid Apps with AngularJS and Ionic

Overview

  1. Native vs Hybrid Apps
  2. Overview of AngularJS (v1)
  3. Introduction to IONIC framework (v1)

Hybrid vs Native Apps

“I want to build an app!”

More Platforms. More Problems.

  • Proficiency in each platform required
  • Entirely separate code bases
  • Timely & expensive development
  • Diminishing returns

Hybrid Apps!

HTML5 that acts like native

Web wrapped in native layer

Direct access to native APIs

Familiar web dev environment

A single code base (web platform!)

“It's not 2007 anymore”
Year Device Processor RAM
2007 iPhone 400 MHz 128 MB
2010 iPhone 4 1 GHz 512 MB
2015 iPhone 6 1.4 GHz dual-core 1 GB
2016 iPhone 7 2.34 GHz Quad-core 2 GB

Web-standards

Have improved!

caniuse.com is lookin' pretty good nowadays

Android is now Chromium-based

iOS users keep their devices up-to-date

https://mixpanel.com/trends/#report/ios_8/from_date:-141,report_unit:day,to_date:0

https://mixpanel.com/trends/#report/android_os_adoption

Native SDKs...

Are Great!

Common UI, APIs, views, navigation, stack history, transitions, interactions, gestures, etc.

Web Technologies You Already

Know & Love

(You'll feel right at home)

Superpowered by

Angular

Extends the HTML vocabulary

Proven for large-scale app development

UI Components using Directives & Services

Sass!

CSS generated from the Sass preprocessor

Quickly give your app its own look and feel

CSS designed to be easily overridden

Variables based with default settings

How it all comes together

  • Your App
  • Ionic
  • Angular
  • WebView (Cordova)
  • Native App

Angular JS

Structural framework for dynamic web applications

Designed by Misko Hevery

First released in June 2012

One of the most popular front-end JS frameworks

Angular Vocabulary

  • Two-way Data Binding
  • Scope
  • Directives
  • Templates
  • Routing
  • Modules
  • Controllers
  • Filters
  • Factory
  • Service
  • Provider

Angular directives

  • ngApp directive

    Applied to specify the root of the application

  • ngInit directive

    Used to evaluate an expression, initialize a JavaScript variable

    
    

  • Angular Expressions

    Evaluated against an Angular scope object

    {{dish.name}}

Angular directives

  • ngModel directive

    binds the input value to a variable within the scope (Two-way data binding)

    
    <div ng-app>
        <label>Name:</label>
        <input type="text" ng-model="yourName">
        <p>Hello {{yourName}}!</p>
    </div>
                        
    Link to the demo

Angular directives

  • ngRepeat directive

    Loops over items in a collection

    
    
    • ...

Angular Modules and Controllers

Angular is built with MVC, MVW in specific!



            

Angular Modules and Controllers

    Model
  • manages the behavior and data of the application domain and responds to requests for information about its state
  • responds to instructions to change state

Angular Modules and Controllers

    View
  • renders the model into a form suitable for interaction, typically a user interface element
  • Multiple views can exist for a single model for different purposes

Angular Modules and Controllers

    Controller
  • receives user input and initiates a response by making calls on model objects
  • instructs the model and viewport to perform actions based on that input

Angular Controller

  • JavaScript object containing attributes/properties and functions

  • Exposes variables and functionality to expressions and directives




            

Angular Filters

  • formatting the value of an expression for display to the end user

  • can be used in view templates, controllers or services

  • Examples: uppercase/lowercase, currency, date, filter, orderBy, etc.


{{dish.price | currency}}

Demo Time!

May the demo gods be with us

Here is a demo of the conFusion App implementation of Models, Views, Controllers

Here is a demo of the conFusion App implementation of Filters

Angular Scope

  • an object that refers to the application model

  • glue between the view and the controller

    • The controller can set properties on the scope
    • The view binds to the properties set by the controller
    • Angular is responsible to keep the two in sync

{{carname}}



            

Angular Forms and Form Validation

  • Two-way Data Binding makes it straightforward to work with forms


   
            


            

Binding Select

Select items can be bound by defining JavaScript object



            

Then bind using ng-options directive



            

Angular Form Validation

  • Angular takes over responsibility for validation
  • Form needs to have a name
  • ng-submit directive specifies the function to call
  • 
    <form class="form-horizontal" name="feedbackForm" ng-submit="sendFeedback()" novalidate>
                
  • Angular has directives for form validation like ng-minlength, ng-maxlength and ng-pattern

Field Properties

  • Angular has pre-defined form field attributes like 'feedbackForm.firstName.$pristine'
  • $pristine - true if form has not been changed
  • $dirty - reverse of $pristine
  • $valid - true if form field/whole form is valid
  • $invalid - reverse of $valid

Field Properties and CSS

Bootstrap provides a lot of CSS classes to enable display of form validation state and messages

  • .has-error
  • .has-warning
  • .has-success
  • .help-block

Demo Time Again!

May the demo gods be with us

Here is a demo of the conFusion App implementation of Form Validation

Dependency Injection

  • Dependency: An object that can be used (a service)
  • Injection: Passing of a dependency to a dependent object so that it can use it.
  • Dependency Injection: Software design pattern that implements inversion of control for resolving dependencies
  • Involves four roles - The service, client, interfaces and injector
  • In Angular, injecor subsystem is used for creating components, resolving their dependencies and providing them to other components
  • 
    
                    

Angular Factory and Service

Angular Services

  • Substitutable objects wired together using DI
  • Helps organizing and sharing code across an app
  • Angular has built-in services like $http, $scope, $rootScope, $location, $parse, $injector
  • These need to be injected using DI

Creating you own services

Five functions that declare services

  • service()
  • factory()
  • provider()
  • constant()
  • value()

Angular Factory


angular.module('confusionApp')
.factory('menuFactory', function()  {
    var menufac = {};
    var dishes = […];
    menufac.getDishes = function(){
        return dishes;
    };
    menufac.getDish = function(index)    
    {
        return  dishes[index];
    };
    return  menufac;
});

---------------------------------------------------------------

angular.module('confusionApp')
.controller('MenuController', ['$scope', 'menuFactory', function($scope, menuFactory)   
{
    $scope.dishes = menuFactory.getDishes();
}]);
            

Angular Service


angular.module('confusionApp')
.service('menuFactory', function(){
    var dishes = […];
    this.getDishes = function(){
        return dishes;
    };
    this.getDish = function(index)    
    {
        return dishes[index];
    };
});

---------------------------------------------------------------

angular.module('confusionApp')
.controller('MenuController', ['$scope', 'menuFactory', function($scope, menuFactory)   
{
    $scope.dishes = menuFactory.getDishes();
}]);
            

Angular Templates

  • Written in HTML
  • Dynamic View = Template + Controller + Model
  • Angular elements and attributes consists of Directives, Markup, Filter and Form controls
  • Eg: the ngInclude directive: used to fetch, compile and include an external HTML fragment
  • It creates a new scope

Single Page Applications

  • Web application or web site that fits in a single page
    • No need to reload the entire page
    • UX like a desktop/native application
    • Most resources are retrieved with a single page load
    • Redraw parts of the page when needed without requiring a full server roundtrip

Traditional websites

Single Page Applications

Challenges with SPA's

  • Search engine optimization
  • Maintaining history
  • Analytics
  • Speeding up the initial page load

SPA's with Angular UI-Router

  • Views based on the state of the application
    • Can change parts of your site using the routing even if the URL does not change
  • Multiple Views
  • Nested Views
  • Dependency injection into the module:
  • 
    angular.module('confusionApp', ['ui.router'])
                    

SPA's with Angular UI-Router

  • Router as a State Machine
  • 
    .config(function($stateProvider, $urlRouterProvider) {
        $stateProvider
        .state('app', {
            url: '/',
            views: {
                'header': { templateUrl : 'views/header.html' },
                'content': { template : '

    To be Completed

    ', controller : 'IndexController' }, 'footer': { templateUrl : 'views/footer.html' } } }) .state('app.aboutus', { url: 'aboutus', views: { 'content@': { template: '

    To be Completed

    ', controller : 'AboutController' } } }); $urlRouterProvider.otherwise('/'); });

SPA's with Angular UI-Router

  • ui-view Directive
    • Indicates where to include the views
    
    
  • ui-sref Directive
    • indicate which state to move to when clicked
    
    
    
    
                    

Demo Time Again!

May the demo gods be with us

Here is a demo of the conFusion App implementation of Angular UI-Router in a SPA

Client-Server Communication

Angular $http
  • Angular service to communicate with servers using the HTTP protocol
  • Uses the browser's XMLHttpRequest/JSONP
  • Requests are asynchronous

    $http({method: 'GET', url: '/dishes'})
        .then(function() {...}, function() {...});
            

Client-Server Communication

$http methods
  • $http.get()
  • $http.put()
  • $http.post()
  • $http.delete()
  • $http.jsonp()
  • $http.head()

Client-Server Communication

$http.get() example

$http.get(baseURL+"dishes")
    .then(
        function(response) {
            $scope.dishes = response.data;
            $scope.showMenu = true;
        },
        function(response) {
            $scope.message = "Error: " + response.status + " " + response.statusText;
        }
    );
            

Client-Server Communication

$http response
  • response.data: string/object containing the body of the message
  • response.status: status code
  • response.headers: header information
  • response.config: configuration object
  • response.statusText: HTTP status text of the response
  • $http.head()

Representational State Transfer

  • Exchange of data using either XML or JSON
  • Four basic design principles:
    • Use HTTP methods explicitly
    • Be stateless
    • Expose directory structure-like URIs
    • Transfer using XML, JSON or both
  • Exploits the use of the HTTP protocol beyond HTTP POST, GET, PUT, DELETE
  • 
    "http://www.conFusion.food/dishes/"
    "http://www.conFusion.food/dishes/123"
    "http://www.conFusion.food/promotions/"
                    

HTTP Methods

  • HTTP POST: Creates a resource
  • 
    POST "http://www.conFusion.food/feedback/"     
                    
  • HTTP PUT: Updates a resource
  • 
    PUT "http://www.conFusion.food/dishes/123"     
                    
  • HTTP DELETE: Removes the resource identified by the URI
  • 
    DELETE "http://www.conFusion.food/dishes/456"    
                    

Angular ng-Resource

  • A module provides a higher level abstraction than $http
  • Not a part of Angular core, needs to be injected through DI
  • 
    angular.module('confusionApp', ['ui.router', 'ngResource'])
                    
  • A higher level abstraction wrapper around a REST API for operations
  • 
    $resource(url, [paramDefaults], [actions], options);
                    

Angular ng-Resource

Example


$resource(baseURL+"dishes/:id", null, {'update':{method:'PUT' }})
    .get({id:0}).$promise.then(
        function(response){
            $scope.dish = response;
            $scope.showDish = true;
        },
        function(response){
            $scope.message = "Error: " + response.status + " " + response.statusText;
        }
    );
            

Demo Time Again!

May the demo gods be with us

Here is a demo of the conFusion App implementation of REST services in a SPA

Complex Lists

  • AngularJS Directive
  • Buttons exposed by swiping
  • Reorder
  • Delete


    
        List Item {{ item.id }}
    

Collection Repeat

  • Replacement for Angular's ng-repeat
  • Inspired by iOS’s UICollectionView
  • Scroll through thousands of items
  • Only renders the viewable items
  • Smooth scrolling!

{{ c.name }}

{{ c.email }}

Swipe To Go Back

  • Swipe back to previous view
  • Interactive transition
  • Benefit of cached views
  • Still updates the app's URL
  • WebView (Cordova) only

Other Components

  • Side Menus
  • Actionsheet
  • Modal
  • Pull To Refresh
  • Spinners
  • Slidebox
  • Infinite Scroll
  • Swipeable List Options
  • Popup
  • Popover
  • Loading Overlay
  • Inputs
  • Buttons
  • etc.

MIT LICENSED

Free to use (even commercially)

Ionicons

700+ MIT licensed font-icons included

ionicons.com

npm install -g ionic cordova

Boilerplate app structure ready for customization

LiveReload both local and native builds

Build and run native apps

Modern

Chromium!

Chromium for Android WebViews

Upgrade Android 4.1+ and above

Same hardware, modern software

Amazing performance improvements

Get Started with Ionic!


Getting started guide
ionicframework.com/getting-started

Documentation
ionicframework.com/docs

Visit the Community Forum
forum.ionicframework.com

Contribute on GitHub
github.com/driftyco/ionic

Demo Time!

May the demo gods be with us

</html>

@ionicframework

http://ionicframework.github.io/ionic-present