web application development - github pages04 angularjs - part 2 19 to define an angularjs app, we...
TRANSCRIPT
Produced by
Department of Computing & Mathematics Waterford Institute of Technology
http://www.wit.ie
Web Application Development David Drohan ([email protected])
MODULES, VIEWS, CONTROLLERS & ROUTES
PART 2
Sec8on Outline 1. Introduc)on–WhyyoushouldbeusingAngularJS
2. Terminology–Thecri:calfounda:onforunderstanding
3. Modules–Reusablefunc:onality
4. Views–UI(UserInterac:on)
5. Controllers–Facilita:ngcommunica:onbetweenthemodelandtheview
6. Routes–Naviga:ngtheview
7. Filters–Changingthewayyouseethings
8. Services–Fiverecipeflavors
9. Direc)ves–ExtendingHTML
10. CaseStudy–Labsinac:on11. Conclusions–Theendisnigh
04ANGULARJS-PART2 3
Sec8on Outline 1. Introduc)on–WhyyoushouldbeusingAngularJS
2. Terminology–Thecri:calfounda:onforunderstanding
3. Modules–Reusablefunc:onality4. Views–UI(UserInterac:on)5. Controllers–Facilita:ngcommunica:onbetweenthemodelandtheview
6. Routes–Naviga:ngtheview7. Filters–Changingthewayyouseethings
8. Services–Fiverecipeflavors
9. Direc)ves–ExtendingHTML
10. CaseStudy–Labsinac:on11. Conclusions–Theendisnigh
04ANGULARJS-PART2 4
Basic Building Blocks WHAT YOU NEED TO BUILD A BASIC ANGULAR WEB APP
04ANGULARJS-PART2 5
Basic Building Blocks * § InstallingAngularJSispreZysimple.Itisjustlikeaddinganyotherlibrary.
§ GototheAngularJS.orgwebsiteanddownloadthestableversionfromthere.
§ Youcanmanagethefiledirectoryas:
04ANGULARJS-PART2 6
Views WHAT THE USER INTERACTS WITH
04ANGULARJS-PART2 7
Basic Building Blocks – Views * § RecallthattheViewistheUserInterface,it’swhattheuserinteractswith§ Whenwri:nganAngularJSapp,wewritethebehaviorandinterac:ontogetheralongsidethepresenta:on(theView)
§ ViewsareocenreferredtoastemplatesinAngular
§ InSPAapps,arenderedtemplate(calledapar)al)isdynamicallyinsertedintoa‘shellpage’-Theshell’stemplateschangesdynamicallyover:me,henceSPA
§ Angularusesdirec)vestoachievethistemplateinser:on
§ Adirec)veisafancynameforafunc:onthat’saZachedtoaDOMelement.§ Direc:veshavetheabilitytoexecutemethods,definebehavior,aZachcontrollersand$scopeobjects,manipulatetheDOM,andmore.
04ANGULARJS-PART2 8
Basic Building Blocks – Views * Direc:ves:ng-◦ Afewofthemostfrequentlyusedare:ü ng-app• DetermineswhichpartofthepagewilluseAngularJS• Ifgivenavalueitwillloadthatapplica:onmodule
ü ng-controller• DetermineswhichJavaScriptControllershouldbeusedforthatpartofthepage
ü ng-model• Determineswhatmodelthevalueofaninputfieldwillbeboundto• Usedfortwo-waydatabinding(nextslide)
04ANGULARJS-PART2 9
04ANGULARJS-PART2 10
2-Way Data Binding Automa)cpropaga:onofdatachanges Modelissinglesourceoftruth
Two Way Data Binding Example *
04ANGULARJS-PART2 11
Two Way Data Binding Example
04ANGULARJS-PART2 12
Two Way Data Binding Example
04ANGULARJS-PART2 13
Basic Building Blocks – Views * l More ng directives ü ng-if=“<model expression>” • Inserts HTML element if expression is true • Does not insert element in the DOM if it is false
ü ng-repeat=“<variable> in <array>” • Repeats the HTML element for each value in the array
04ANGULARJS-PART2 14
Basic Building Blocks - Views
AngularExpression:{{}}◦ Usedtoinsertmodelvaluesdirectlyintotheview◦ (anextractfromdona)ons.ejs)
04ANGULARJS-PART2 15
Modules REUSABLE FUNCTIONALITY
04ANGULARJS-PART2 16
Basic Building Blocks – Modules Modulesareawayoforganizingyourcodeinwhichyousplituptheworkbetweendifferentsec:onsofyourcoderatherthanwri:ngasinglehugeapplica:on.
Anapplica:onmodulecanincludetheothermodules(sec:ons)bylis:ngthemasdependencies.
04ANGULARJS-PART2 17
angular.module(<name>,[<dependencies>]);
Basic Building Blocks – Modules Modulesareawayoforganizingyourcodeinwhichyousplituptheworkbetweendifferentsec:onsofyourcoderatherthanwri:ngasinglehugeapplica:on.
Anapplica:onmodulecanincludetheothermodules(sec:ons)bylis:ngthemasdependencies.
04ANGULARJS-PART2 18
Module Defini8on *
Defineamodule:
Defineamodulewithdependenciesonothermodules:
Getanexis:ngmodule:
04ANGULARJS-PART2 19
TodefineanAngularJSapp,wefirstneedtodefineanangular.module.AnAngularmoduleissimplyacollec:onoffunc:onsthatarerunwhentheapplica:onis“booted.”Allappshaveatleastonemodule.
The Applica8on Module
HTMLFRAGMENT JAVASCRIPTFRAGMENT
AngularJSprovidesawayforyoutobindyourmainmoduletotheHTMLdocumentusingtheng-appdirec:ve.
04ANGULARJS-PART2 20
Module Phases CONFIG
The config phase happens earlywhile theapplica:on is s:ll being built. Only theproviderservicesandconstantservicesarereadyforD.I.atthisstage.
RUN
The runphasehappensonce themodulehasloadedallofitsservicesanddependencies.
var module = angular.module('myModule', []); module.config([function() { alert('I run first'); }]); module.run([function() { alert('I run second'); }]);
04ANGULARJS-PART2 21
Module Components & D.I. AngularJSletsyouinjectservices(eitherfromitsownmoduleorfromothermodules)withthefollowingpaZern:
var module = angular.module('myModule', []); module.service('serviceA', function() { ... }); module.service('serviceB', function(serviceA) { ... });
04ANGULARJS-PART2 22
Dona8on MVC App using Modules *
04ANGULARJS-PART2 23
Dona8on MVC App using Modules
04ANGULARJS-PART2 24
Modules – App Design Recommenda)ons:§ Amoduleforeachfeature.§ Amoduleforeachreusablecomponent
(especiallycustomdirec:vesandfilters)
§ Andanapplica:onlevelmodulewhichdependsontheabovemodulesandcontainsanyini:aliza:oncode.
04ANGULARJS-PART2 25
Controllers FACILITATING COMMUNICATION BETWEEN THE MODEL AND THE VIEW
04ANGULARJS-PART2 26
04ANGULARJS-PART2 27
Theinterfacebetweenthemodelandtheview Containsthecodebehindtheview Trytokeeplightweight
Basic Building Blocks - Controller
04ANGULARJS-PART2 28
Basic Building Blocks - Scope § A$scopeisanobjectthat:esaview(aDOMelement)tothecontroller
§ IntheModel-View-Controllerstructure,this$scopeobjectbecomesthemodel.
§ Itprovidesanexecu%oncontextthatisboundtotheDOMelement(anditschildren).
§ Althoughitsoundscomplex,the$scopeisjustaJavaScriptobject.§ Boththecontrollerandtheviewhaveaccesstothe$scopesoitcanbeused
forcommunica:onbetweenthetwo.§ This$scopeobjectwillhouseboththedataandthefunc:onsthatwe’llwant
torunintheview,aswe’llsee.
Basic Building Blocks - Scope $scope◦ Containsdata(i.e.models)andmethods(i.e.func:ons)◦ Istheenginefor2-waydatabinding◦ Canaddyourownproper:es◦ $scope.<mynewproperty>=<value>;
Controllerfunc:ontakesatleastoneparameter:$scope
04ANGULARJS-PART2 29
Controllers and Scope *
04ANGULARJS-PART2 30
‘Donate’Example
Controllers and Scope *
04ANGULARJS-PART2 31
‘Donate’Example
Controllers and Scope *
04ANGULARJS-PART2 32
‘Donate’Example
Controllers and Scope
04ANGULARJS-PART2 33
‘Donate’Example
Routes NAVIGATING THE VIEW
04ANGULARJS-PART2 34
Basic Building Blocks - Rou8ng AllowsSPAsbehaveliketradi:onalWebApps/sites§ forward/backbuZonsupport§ deep-linkingtospecificcontent§ Old-styleAJAXWebAppsdidn’tsupportrou:ng(addressabilityproblem)
§ Advantages§ Bookmarking,linksharing,directnaviga:on
§ TwoSolu:onApproaches:§ Hash-based,e.g.hZp://domain_name/#/some_app_url§ PushState,e.g.hZp://domain_name/some_app_urlAngularsupportsboth(nextslide)
04ANGULARJS-PART2 35
Basic Building Blocks - Rou8ng PathsdefaulttoHash-basedmode◦ ExampleURL.◦ hZp://www.mysite.com/#/users
CanuseHTML5modebyconfiguringthe$loca)onProvider(nextfewslides)◦ Ex.◦ //Inject$loca:onProviderintothemoduleusingconfig$loca:onProvider.html5Mode(true);
◦ ExampleURL:◦ hZp://www.mysite.com/users
04ANGULARJS-PART2 36
Basic Building Blocks - Rou8ng UsedifferentviewsfordifferentURLfragments Makesuseoftemplatepar:als◦ Templatesthatarenotawholewebpage(i.e.partofapage)◦ Usedinconjunc:onwiththeng-viewdirec:ve◦ ng-viewdetermineswherethepar:alwillbeplaced◦ Canonlyhaveoneng-viewperpage
04ANGULARJS-PART2 37
Basic Building Blocks - Rou8ng Enablebyinjec:ngthe$routeProvider◦ myApp=angular.module(‘myApp’,[‘ngRoute’]);myApp.config([‘$routeProvider’,func:on($routeProvider){…}]);
$routeProvider.when(<path>,{<route>});◦ Definesanewroutethatusesthegivenpath◦ Thepathmayhaveparameters
◦ Parametersstartwithacolon(‘:’)◦ Ex-‘/user/:userId’ ($routeParams.userid)
◦ Typicalroutefields:◦ controller=Thenameofthecontrollerthatshouldbeused◦ templateUrl=Apathtothetemplatepar:althatshouldbeused
$routeProvider.otherwise({<route>});◦ Typicalroutefields:
◦ redirectTo:‘<path>’
API:hZp://docs.angularjs.org/api/ngRoute.$routeProvider04ANGULARJS-PART2 38
ModuleDependency
RouteObject
Rou8ng – The Shell Page ng-viewdirec:ve–renderedtemplateofthecurrentrouteis
§ dynamicallyinsertedintotheshellpage(index.ejs)
§ URLchangeàTemplatechange+Controllerinstan:a:on
§ Shellpage=Layoutpage.
04ANGULARJS-PART2 39
index.ejs
direc:ve
Case Study LABS IN ACTION
04ANGULARJS-PART2 40
Demo Applica8on
04ANGULARJS-PART2 41
About the Original Author JamesSpeirs
Applica:onFounda:ons
OITCoreServices BrighamYoungUniversity
04ANGULARJS-PART2 42
Questions?
04ANGULARJS-PART2 43