Mobile HTML5 websites and Hybrid Apps with AngularJS How to code today with tomorrow tools - mobile edition Carlo Bonamico - @carlobonamico NIS s.r.l. [email protected] [email protected] Web 0
Aug 27, 2014
MobileHTML5websitesandHybridAppswithAngularJS
Howtocodetodaywithtomorrowtools-mobileeditionCarloBonamico-@carlobonamico
NISs.r.l.
Web
0
AngularJSletsyouusetodaythefeaturesofnext-generationwebstandards,
makingfront-enddevelopmentmoreproductiveandfunWhat'sbetter,itprovidesits"magic"toolstobothwebANDmobileapps
databinding,dependencyinjectionmodularity,composableandevent-drivenarchitecture
This code-based interactivetalkwillsharesomelessonslearned
howtostructureapplicationstunebandwidthandperformanceinteractwithmobile-specificelementssuchastouch,sensorsnative-lookingUXwithIonicFramework
Inshort
1
Idonotwanttojointhefight;-)
Thewebtendstoalwaysbemorepowerfulthanpeoplethink!andthegapwithnativewillonlybecomesmallerwithtime
Therearemanyusecasesforweb-basedsitesandhybridapps(HTML5packedinanapp)
avoidinginstallondeviceensuringalwayslatestversionplatformsupport:iOS,Android,WindowsPhone...easierandmorefamiliardevelopmentworkflow
Andmyfavorite...touseAngularmagic!
WebvsNative
2
OpenSourceframweworkfast-growinggreatcommunity
http://www.angularjs.org
LetsyouadoptfuturewebarchitectureandtoolstodayanticipateWebComponentsandEcmaScript6
Createmodular,robust,testableapps
SowhyAngularJS
3
DependencyInjectionsplitcomponentdefinitionfromcomponentwiring
Modulecompositione.g.commonmodulesmobile-onlycomponentsdesktop-onlycomponents
Whatyouget:writelesscode,reusemorethecodeyouwrite!
Angulargivesstructureandmodularity
4
...isn'taweb/JSMobileappunusablyslow?
Let'stry...
ThispresentationisanAngular-basedSinglePageApplication
NowwelaunchitonaphoneandexploreitwithChromeusbdebugging
But...
5
about:inspect
enableportforwardingfromlaptoptophoneopen http://localhost:8000 onthephone
Discoveringthedevice
6
MonitoringCPUusageandFPS
7
Inspectingthepageonthephone
8
AView:index.htmlastyle.css
peppered-upwithAngularJS'ng-something'directivesAmodel
data:slides.mdcode:arrayofslideobject
Acontrollerscript.js
What'sinside
9
varslide={number:i+1,title:"Title"+i,content:"#Title\nmarkdownsample",html:"",background:"backgroundSlide"};
Themodel
10
ngSlides.service('slidesMarkdownService',function($http){varconverter=newShowdown.converter();return{getFromMarkdown:function(path){varslides=[];
$http({method:'GET',url:path}).success(function(data,status,headers,config){varslidesToLoad=data.split(separator);//twodashesfor(i=0;i<slidesToLoad.length;i++){varslide={content:slidesToLoad[i],//..initotherslidefields};slide.html=converter.makeHtml(slide.content);slides.push(slide);}});returnslides;}}})
Aservicetoloadslidesfrommarkdown
11
bindingthemodeltothehtml
<bodyng-app="ngSlides"ng-class="slides[currentSlide].background"ng-controller="presentationCtrl">
<divid="slidesContainer"class="slidesContainer"><divclass="slide"ng-repeat="slideinslides"ng-show="slide.number==currentSlide">
<divng-bind-html="slide.html"></div>
<h4class="number">{{slide.number}}</h4>
</div>
</div></body>
andaverysimplecssforpositioningelementsinthepage
Asimpledeclarativeview
12
ngSlides.controller("presentationCtrl",function($scope,$http,$rootScope,slidesMarkdownService){
$scope.slides=slidesMarkdownService.getFromMarkdown('slides.md');
$scope.currentSlide=0;
$scope.next=function(){$scope.currentSlide=$scope.currentSlide+1;
};
$scope.previous=function(){$scope.currentSlide=$scope.currentSlide-1;};
});
Acontrollerfocusedoninteraction
13
Anysufficientlyadvancedtechnologyisindistinguishablefrommagic.ArthurC.Clarcke
Addsearchwithintheslidesinoneline
<divng-repeat="slideinslides|filter:q">...</div>
whereqisavariablecontainingthesearchkeyword
AngularJSmagic
14
Two-wayDatabindingsplittheviewfromthelogic {{slide.number}}
DependencyInjectiongivesdecoupling,testability&enrichingofcodeandtags
functionSlidesCtrl($scope,SlidesService){SlidesService.loadFromMarkdown('slides.md');}
Thepowerofcomposition-ofmodulesmodule('slides',['slides.markdown'])directives<h1ng-show='enableTitle'ng-class='titleClass'>..</h1>filtersslideinslides|filter:q|orderBy:title|limit:3...
AngularJSmagicismadeof
15
Butwhat'smoreimportant,less"lowvalue"codemorereadablecode
Soyoucanconcentrateonyourapplicationidea
AngularJSisopinionatedbutitwillletyoufollowadifferentwayincaseyoureallyneedit
SoAngularletyouwritelesscode
16
SpeedcanmeanmanythingsUXspeedvsprocessingspeed
databindingletsyoueasilydisplaydataprogressivelyclient-siderichmodelsandfilteringletyourespondquicklytouserinput
networkdelaysvsappresponsetimes
Butthechallengeisn'tjustbeingperformantBeinganawesomemobileapp
handlegesturesrespectuserexpectations(e.g.swipeablecards)managenavigationmanageappstateandoff-lineavailability
So,backtoourmobileapps...
17
reduceDOMmanipulationusesimplemarkupmoveallstylingtoCSS
noJSAnimation,useCSS3HWacceleratedtransitions
optimizeyourdatabindingshttps://www.exratione.com/2013/12/considering-speed-and-slowness-in-angularjs/
bindonceandtargetedbindingshttps://github.com/Pasvaz/bindonce
PerformanceTips
18
TunewithAngularJSBataranghttps://github.com/angular/angularjs-batarang
PerformanceTuning
19
Thebiggestcostisopeningaconnection,nottransferringfiles
useHTTPKeep-aliveenableGZipcompressionhttps://developers.google.com/speed/pagespeed/module
LocalmanipulationofdatagreatlyreducesnetworktrafficLocalDBandsync
Bandwidthoptimizations
20
Moduleng-touchfastclick:eliminatethe300msdelayeasilymanageswipes <divng-swipe-left="next()">
foradvancedcases:ionic-gestureshammer.js
SupportTouchandGestures
21
OnthedeviceSessionstorageLocalstoragelawnchairPouchDBhttp://pouchdb.com/
InthecloudMongolabhttp://mongolab.comFirebasewithAngularFirehttps://www.firebase.comBaasBoxhttp://www.baasbox.com
Storingstate
22
HTML5standardAPIssupportonlysomesensorslocation(verygoodsupport)orientationacceleration
AdditionalsensorsrequirethePhoneGapAPIs
needtowrapallcallbackswith$apply()orbetter,adedicatedservice
tonotifyAngularofchangesoccurredoutofitslifecycle
Managingsensors
23
Chromeremotedebuggingandscreencasthttps://developers.google.com/chrome-developer-tools/docs/remote-debugging
chrome://inspect/#devices
Emulatedeviceresolutions,DPIs,sensors:ChromeemulatorRippleEmulatorhttp://emulate.phonegap.com
Howtodevelopformobile?
24
Development-timestructuremultiplefilescomponent/dependencymanagers(bower...)
Compile-timestructurelimitednumberoffilesconcatenationminification
UseatoolchainMarcelloTeodori'stalkonJSPowerTools
Issues
25
firstphase:prototypingonaDesktopbrowsersecondphase:unittesting
wayeasierwithAngularJSthirdphase:ondevicetesting
Chromeon-devicedebugging
Testablemobileapps?
26
Phonegaphttp://phonegap.com/https://cordova.apache.org/
PhonegapBuildhttp://build.phonegap.com
ChromeAppsforMobilehttp://blog.chromium.org/2014/01/run-chrome-apps-on-mobile-using-apache.html
Packagingappsformarkets
27
CordovaBrowseryouinstallitonceandopenyourcodeonyourwebservercontinuousrefreshwithoutreinstallingtheapp
Developmenttips
28
orbettertheUX-UserExperience?Comparingmobilewebframeworks
http://moduscreate.com/5-best-mobile-web-app-frameworks-ionic-angulalrjs/
JQueryMobilewidgets-onlyDOM-heavvyAngularintegrationisnotsimple(differentlifecycles)atmost,JQMobileforCSSandAngularfornavigationandlogic
WhatabouttheUI?
29
AngularJS-based,OpenSourceperformanceobsessedmobile-lookingextensible
http://ionicframework.com/http://ionicframework.com/getting-started/http://ionicframework.com/docs/guide/
EnterIonicFramework
30
IonicCSSIonicIconsIonicDirectives
andsupportTooling
What'sinside?
31
elegantyetverylightweight
<divclass="list"><divclass="itemitem-divider">CandyBars</div><aclass="item"href="#">Butterfinger</a></div>
http://ionicframework.com/docs/
3Danimations,HWaccelerated
sass-basedforcustomtheming500freeicons(ionicons)
IonicCSS
32
mobilenavigationandinteractions
<ion-list><ion-itemng-repeat="iteminitems"item="item"can-swipe="true"option-buttons="itemButtons"></ion-item></ion-list>
servicesforgesturesnavigation
http://ionicframework.com/docs/api
IonicDirectives
33
http://plnkr.co/edit/Mcw6F2BQP3RbB8ZhBYRl?p=preview
Let'splayaround...(withLiveReload)
34
basedonUI-Routerhttp://angular-ui.github.io/ui-router
sub-views(e.g.Tabs)per-viewnavigationhistory
UIGalleryhttp://ionicframework.com/present-ionic/slides/#/16
Navigation
35
PhoneGapbasedbuildchain
$npm-ginstallionic$ionicstartmyApptabs
$cdmyApp$ionicplatformaddios$ionicbuildios$ionicemulateios
IonicTooling
36
AngularJS2.0willbeMobileFirstperformancebrowsersupporthttp://blog.angularjs.org/2014/03/angular-20.html
WebComponentsonMobile
EcmaScript6- Object.observe() ->ultrafastbinding
TheFuture
37
AngularJScanbeviableonmobileinteractivityinplainHTML5views
AngularJSchangesyourwayofworking(forthebetter!)letyoufreeofconcentratingonyourideasmakesforawayfasterdevelopmentcyclemakesforawayfasterinteractionwithcustomercycleessentialforContinuousDelivery!
Lessonslearnt
38
Likeallthemagicwands,youcouldenduplikeMikeyMouseastheapprenticesorcererGettingstartedisveryeasyButtogofurtheryouneedtolearnthekeyconcepts
scopesdependencyinjectiondirectivespromises
Sogetyourtraining!Codemotiontraining(june2014)http://training.codemotion.it/
NEW!AdvancedAngularJScoursecominginJuly-September2014
Lessonslearnt
39
Bookshttp://www.ng-book.com/-Recommended!AngularJSand.NEThttp://henriquat.re
Onlinetutorialsandvideotrainings:http://www.yearofmoo.com/http://egghead.io
AlllinksandreferencefrommyCodemotionWorkshophttps://github.com/carlobonamico/angularjs-quickstarthttps://github.com/carlobonamico/angularjs-quickstart/blob/master/references.md
FulllabfrommyCodemotionWorkshophttps://github.com/carlobonamico/angularjs-quickstart
Tolearnmore
40
OptimizingAngularJSformobilehttp://blog.revolunet.com/angular-for-mobilehttp://www.ng-newsletter.com/posts/angular-on-mobile.htmlhttps://www.youtube.com/watch?v=xOAG7Ab_Oz0http://www.bennadel.com/blog/2492-What-A-Select-watch-Teaches-Me-About-ngModel-And-AngularJS.htm
WebComponentshttp://mozilla.github.io/brick/docs.htmlhttp://www.polymer-project.org/
Evenmore
41
Exploretheseslideshttps://github.com/carlobonamico/mobile-html5-websites-and-hybrid-apps-with-angularjshttps://github.com/carlobonamico/angularjs-future-web-development-slides
Mypresentationshttp://slideshare.net/carlo.bonamico
Followmeat@carlobonamico/@nis_srlwillpublishtheseslidesinafewdays
AttendmyCodemotiontrainingshttp://training.codemotion.it/
Thankyou!
42