modified from a presentaon by jussi...

90
Intro to SPA framework Modified from a presenta6on by Jussi Pohjolainen

Upload: others

Post on 09-Jul-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

IntrotoSPAframeworkModifiedfromapresenta6onby

JussiPohjolainen

Page 2: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

RiseoftheResponsiveSinglePageApp

Image:hBp://johnpolacek.github.io/scrolldeck.js/decks/responsive/

Page 3: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

Responsive

•  Unifiedacrossexperiences

•  Canbeembeddedasmobileapp

•  BeBerdeploymentand&maintanence

•  Mobileusersneedtogetaccesstoeverything

Image:hBp://coenraets.org/blog/wp---content/uploads/2011/10/directory11.png

Page 4: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

Single---pageApplica6ons(SPA)

•  Webappthatfitsonasinglewebpage– FluidUX,likedesktopapp– ExampleslikeGmail,Googlemaps

•  Htmlpagecontainsmini---views(HTMLFragments)thatcanbeloadedinthebackground

•  Noreloadingofthepage,•  Requireshandlingofbrowserhistory,naviga7onandbookmarks

Page 5: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

JavaScript

•  SPAsareimplementedusingJavaScriptandHTML

Page 6: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

ChallengesinSPA•  DOMManipula7on

–  Howtomanipulatetheviewefficiently?•  History

– WhathappenswhenpressingbackbuBon?•  Rou7ng

–  ReadableURLs?•  DataBinding

–  Howbinddatafrommodeltoview?•  ViewLoading

–  Howtoloadtheview?•  Lotofcoding!Youcoulduseaframeworkinstead...

Page 7: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

Single-pageApplica6on

Singlepageappstypicallyhave“applica6onlike”interac6ondynamicdataloadingfromtheserver-sideAPIfluidtransi6onsbetweenpagestatesmoreJavaScriptthanactualHTML

Theytypicallydonothavesupportforcrawlers(notforsitesrelyingonsearchtraffic)supportforlegacybrowsers(IE7orolder,dumbphonebrowsers)

Page 8: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

SPAsAreGoodFor…

•  “App-likeuserexperience”•  Bindingtoyourown(or3rdparty)RESTfulAPI•  ReplacementforFlashorJavainyourwebpages

•  Hybrid(na6ve)HTML5applica6ons•  MobileversionofyourwebsiteTheSPAsweetspotislikelynotonwebsites,butoncontent-richcross-pla;ormmobileapps

Page 9: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

PJAX

PjaxisatechniquethatallowsyoutoprogressivelyenhancenormallinksonapagesothatclicksresultinthelinkedcontentbeingloadedviaAjaxandtheURLbeingupdatedusingHTML5pushState,avoidingafullpageload.Inbrowsersthatdon'tsupportpushStateorthathaveJavaScriptdisabled,linkclickswillresultinanormalfullpageload.ThePjaxU6litymakesiteasytoaddthisfunc6onalitytoexis6ngpages.

hBp://yuilibrary.com/yui/docs/pjax/

Page 10: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

SPAsandOtherWebAppArchitecturesServer-side Server-side+AJAX PJAX SPA

What Serverround-triponeveryappstatechange

Renderini6alpageonserver,statechangesontheclient

Renderini6alpageonserver,statechangesonserver,injectintoDOMonclient-side

Servesta6cpageskeletonfromserver;rendereverychangeonclient-side

How UIcodeonserver;links&formpos6ng

UIcodeonbothends;AJAXcalls,uglyserverAPI

UIcodeonserver,clienttoinjectHTTP,serverAPIifyoulike

UIcodeonclient,serverAPI

Easeofdevelopment

UX&responsiveness

Robots&oldbrowsers

Who’susingit? Amazon,Wikipedia;banks,mediasitesetc.

Facebook?;widgets,search

TwiBer,Basecamp,GitHub

Google+,Gmail,FT;mobilesites,startups

FROM:LAURISVAN

Page 11: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

ANGULAR_JS

Page 12: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

AngularJS

•  SinglePageAppFrameworkforJavaScript•  Implementsclient---sideMVCpaBern

– Separa6onofpresenta6onfrombusinesslogicandpresenta6onstate

•  NodirectDOMmanipula6on,lesscode•  Supportforallmajorbrowsers•  SupportedbyGoogle•  Largeandfastgrowingcommunity

Page 13: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

InterestinAngularJS

GoogleProduct=Stellarlevel&qualityofsupportGoogleBacking=Increasedcredibility&interest

FromGaryArora

Page 14: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

AngularJS–MainConcepts

•  Templates•  Direc6ves•  Expressions•  Databinding•  Scope

•  Controllers•  Modules•  Filters•  Services•  Rou6ng

Page 15: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

AnatomyofaBackboneSPA•  Applica6onasa‘singleton’referenceholder

•  Routerhandlesthenaviga6onandtogglesbetweenviews

•  ModelssynchronizewithServerAPI

•  Bulkofthecodeinviews•  AllHTMLintemplates

Model / Controller

View Template

emits events

changesusing

changesinstantiates

using

Backend

DOM

synchronizeschanges with

Application

Router

initializes

toggles

FROM:LAURISVAN

Page 16: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

FromGaryArora

Page 17: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

SPAClient-ServerCommunica6on•  HTMLandalltheassetsareloadedinfirstrequest

•  Addi6onaldataisfetchedoverXMLHTTPRequest

•  Ifyouwanttogoreal-6me,WebSockets(socket.io)canhelpyou

•  Whenitgetsslow,clusterthebackendbehindacachingreverseproxylikeVarnish

Storage

Business Logic

Browser

Presentation / Server API

XMLHTTP-Request WebSocket

HTTP Server

Browser(page load)

REST API Socket API

Data storage

BusinessLogic

HTTP / * HTTP / JSON TCP / JSON

Auth & Access Control

FROM:LAURISVAN

Page 18: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

HOWITWORKS?

FromRouson

Page 19: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

HOWITWORKS?

FromRouson

Page 20: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

HOWITWORKS?

FromRouson

Page 21: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

GETTINGSTARTEDWITHANGULAR_JS

Page 22: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

BasicConcepts

•  1)Templates– HTMLwithaddi6onalmarkup,direc6ves,expressions,filters...

•  2)Direc7ves– ExtendHTMLusingng-app,ng-bind,ng-model

•  3)Filters– Filtertheoutput:filter,orderBy,uppercase

•  4)DataBinding– Bindmodeltoviewusingexpressions{{ }}

Page 23: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

FirstExample–Template<!DOCTYPE html> <html> <head> <title>Title</title> <meta charset="UTF-8" /> <style media="screen"></style> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> </head> <body> <div ng-app> <!-- store the value of input field into a variable name --> <p>Name: <input type="text" ng-model="name"></p> <!-- display the variable name inside (innerHTML) of p --> <p ng-bind="name"></p> </div> </body> </html>

Template

Page 24: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

2)Direc6ves•  Direc7vesapplyspecialbehaviortoaBributesorelementsinHTML– ABachbehaviour,transformtheDOM

•  Somedirec6ves– ng-app

•  Ini6alizestheapp– ng-model

•  Stores/updatesthevalueoftheinputfieldintoavariable– ng-bind

•  ReplacethetextcontentofthespecifiedHTMLwiththevalueofgivenexpression

Page 25: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

AboutNaming

•  AngularJSHTMLCompilersupportsmul6pleformats– ng-bind

•  RecommendedFormat

– data-ng-bind •  RecommendedFormattosupportHTMLvalida6on

– ng_bind, ng:bind, x-ng-bind •  Legacy,don'tuse

Page 26: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

LotofBuiltinDirec6ves

•  ngApp •  ngClick •  ngController •  ngModel •  ngRepeat •  ngSubmit

•  ngDblClick •  ngMouseEnter •  ngMouseMove •  ngMouseLeave•  ngKeyDown •  ngForm

Page 27: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

2)Expressions

•  AngularexpressionsareJavaScript---likecodesnippetsthatareusuallyplacedinbindings– {{ expression }}.

•  ValidExpressions– {{ 1 + 2 }} – {{ a + b }} – {{ items[index] }}

•  Controlflow(loops,if)arenotsupported!•  Youcanusefilterstoformatorfilterdata

Page 28: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

Example<!DOCTYPE html> <html> <head> <title>Title</title> <meta charset="UTF-8" /> <style media="screen"></style> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> </head> <body> <div ng-app> <p>Number 1: <input type="number" ng-model="number1"></p> <p>Number 2: <input type="number" ng-model="number2"></p> <!-- expression --> <p>{{ number1 + number2 }}</p> </div> </body> </html>

Direc6ve

Expression

Direc6ve

Page 29: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

ng---initandng---repeatdirec6ves

<!DOCTYPE html> <html data-ng-app=""> <head> <title>Title</title> <meta charset="UTF-8" /> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> </head> <body> <div data-ng-init="names = ['Jack', 'John', 'Tina']"> <h1>Cool loop!</h1> <ul> <li data-ng-repeat="name in names">{{ name }}</li> </ul> </div> </body> </html>

Page 30: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

3)Filter

•  Withfilter,youcanformatorfiltertheoutput•  Forma[ng

– currency, number, date, lowercase, uppercase

•  Filtering– filter, limitTo

•  Other– orderBy, json

Page 31: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

UsingFilters---Example<!DOCTYPE html> <html data-ng-app=""> <head> <title>Title</title> <meta charset="UTF-8" /> <style media="screen"></style> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> </head> <body> <div data-ng-init="customers = [{name:’tina'}, {name:’jack'}]"> <h1>Cool loop!</h1> <ul> <li data-ng-repeat="customer in customers | orderBy:'name'"> {{ customer.name | uppercase }}</li> </ul> </div> </body> </html> Filter

Filter

Page 32: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

UsingFilters---Example<!DOCTYPE html> <html data-ng-app=""> <head> <title>Title</title> <meta charset="UTF-8" /> <style media="screen"></style> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> </head> <body> <div data-ng-init= "customers = [{name:'jack'}, {name:'tina'}, {name:'john'}, {name:'donald'}]"> <h1>Customers</h1> <ul> <li data-ng-repeat="customer in customers | orderBy:'name' | filter:'john'">{{ customer.name | uppercase }}</li> </ul> </div> </body> </html>

Page 33: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

UsingFilters–UserInputFilterstheData<!DOCTYPE html> <html data-ng-app=""> <head> <title>Title</title> <meta charset="UTF-8" /> <style media="screen"></style> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> </head> <body> <div data-ng-init= "customers = [{name:'jack'}, {name:'tina'}, {name:'john'}, {name:'donald'}]"> <h1>Customers</h1> <input type="text" data-ng-model="userInput" /> <ul> <li data-ng-repeat="customer in customers | orderBy:'name' | filter:userInput">{{ customer.name | uppercase }}</li> </ul> </div> </body> </html>

Page 34: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

APIReferencehBps://docs.angularjs.org/api/ng/filter/filter

Page 35: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

VIEWS,CONTROLLERS,SCOPE

Page 36: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

Model–View---Controllers

•  Controllersprovidethelogicbehindyourapp.– SousecontrollerwhenyouneedlogicbehindyourUI

•  AngularJSappsarecontrolledbycontrollers•  Useng---controllertodefinethecontroller•  ControllerisaJavaScriptObject,createdbystandardJSobjectconstructor

Page 37: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

Model–View---Controllers

acontrollerisaJavaScriptfunc6on○Itcontainsdata○Itspecifiesthebehavior○Itshouldcontainonlythebusinesslogicneededforasingleview.

Page 38: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

View,ControllerandScope

View(htmlfragment)

Controller $scope

$scope isanobjectthatcanbeusedtocommunicatebetween

ViewandController

Page 39: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

Scope

Page 40: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

<!DOCTYPE html> <html> <head> <title>Title</title> <meta charset="UTF-8" /> <style media="screen"></style> <script src="https://ajax.googleapis.com/ ajax/libs/angularjs/1.4.8/angular.min.js"> </script> </head> <body> <div data-ng-app="myApp" data-ng-controller="NumberCtrl"> <p>Number: <input type="number" ng-model="number"></p> <p>Number = {{ number }}</p> <button ng-click="showNumber()">Show Number</button> </div> <script> var app = angular.module('myApp', []); app.controller('NumberCtrl', function($scope) { $scope.number = 1; $scope.showNumber = function(){ window.alert( "your number= " + $scope.number ); }; }); </script> </body> </html>

Page 41: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

Modules

•  Moduleisanreusablecontainerfordifferentfeaturesofyourapp– Controllers,services,filters,direc6ves...

•  Ifyouhavealotofcontrollers,youarepollu7ngJSnamespace

•  Modulescanbeloadedinanyorder•  Wecanbuildourownfiltersanddirec7ves!

Page 42: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

WhentouseControllers

•  Usecontrollers– setuptheini6alstateof$scopeobject– addbehaviortothe$scopeobject

•  Donot– ManipulateDOM(usedatabinding,direc7ves)– Formatinput(useformcontrols)– Filteroutput(usefilters)– Sharecodeorstate(useservices)

Page 43: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

AppExplained

•  Apprunsinsideng-app (div)•  AngularJSwillinvoketheconstructorwitha$scope–object

•  $scopeisanobjectthatlinkscontrollertotheview

Page 44: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

MODULES,ROUTES,SERVICES

Page 45: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

Example:OwnFilter// declare a module

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

filter

// configure the module. // in this example we will create a greeting myAppModule.filter('greet', function() {

return function(name) { ' + name + '!'; return 'Hello,

};

});

Page 46: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

HTMLusingtheFilter

<div ng-app="myApp"> <div> {{ 'World' | greet }}

</div> </div>

Page 47: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

TemplateforControllers// Create new module 'myApp' using angular.module method. // The module is not dependent on any other module var myModule = angular.module('myModule',

[]);

myModule.controller('MyCtrl', function ($scope) {

// Your controller code here!

});

Page 48: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

Crea6ngaControllerinModulevar myModule = angular.module('myModule',

[]);

myModule.controller('MyCtrl', function ($scope) {

var model = { "firstname": "Jack",

"lastname": "Smith" };

$scope.model = model; $scope.click = function() {

alert($scope.model.firstname);

};

});

Page 49: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

<!DOCTYPE html> <html> <head>

<title>Title</title> <meta charset="UTF-8" /> <style media="screen"></style> <script <script

src="../angular.min.js"></script> src="mymodule.js"></script>

</head> <body> <div ng-app="myModule"

<div ng-controller="MyCtrl">

<p>Firstname: <input type="text" ng-model="model.firstname"></p> <p>Lastname: <input type="text" ng-model="model.lastname"></p>

<p>{{model.firstname + " " + model.lastname}}</p>

<button ng-click="click()">Show Number</button>

</div>

</div> </body>

</html>

ThisisnowthemodelobjectfromMyCtrl.Modelobjectissharedwithview

andcontroller

Page 50: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

ROUTING

Page 51: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

Rou6ng

•  SincewearebuildingaSPAapp,everythinghappensinonepage– Howshouldback---bu]onwork?– Howshouldlinkingbetween"pages"work?– HowaboutURLs?

•  Rou7ngcomestorescue!

Page 52: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

<html data-ng-app="myApp"> <head> <title>Demonstration of Routing - index</title>

<meta charset="UTF-8" /> src="../angular.min.js" type="text/javascript"></script> src="angular-route.min.js" type="text/javascript"></script> src="myapp.js" type="text/javascript">

<script <script <script

</script> </head>

<body> <div data-ng-view=""></div>

</body> </html>

Thecontentofthiswillchangedynamically

Wewillhavetoloadaddi6onal

module

Page 53: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

// This module is dependent on ngRoute. Load ngRoute // before this. var myApp = angular.module('myApp', ['ngRoute']);

views.

// Configure routing. myApp.config(function($routeProvider) {

// Usually we have different controllers for different // In this demonstration, the controller does nothing. $routeProvider.when('/', {

templateUrl: 'view1.html', controller: 'MySimpleCtrl' });

$routeProvider.when('/view2', { templateUrl: 'view2.html', controller: 'MySimpleCtrl' });

$routeProvider.otherwise({ redirectTo: '/' });

}); // Let's add a new controller to MyApp myApp.controller('MySimpleCtrl', function ($scope) {

});

Page 54: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

Views

•  view1.html:<h1>View 1</h2> <p><a href="#/view2">To View 2</a></p>

•  view2.html:<h1>View 2</h2> <p><a href="#/view1">To View 1</a></p>

Page 55: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

WorkinginLocalEnvironment

•  Ifyouget"crossoriginrequestsareonlysupportedforHTTP"..

•  Either– 1)Disablewebsecurityinyourbrowser– 2)UsesomewebserverandaccessfileshBp://..

•  Todisablewebsecurityinchrome–  taskkill /F /IM chrome.exe –  "C:\Program Files (x86)\Google\Chrome\Application

\chrome.exe" --disable-web-security --allow-file-access- from-files

Page 56: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

EXERCISE4:ROUTING

Page 57: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

Services•  View---independentbusinesslogicshouldnotbeinacontroller–  Logicshouldbeinaservicecomponent

•  Controllersareviewspecific,servicesareapp---spesific– Wecanmovefromviewtoviewandserviceiss6llalive

•  Controller'sresponsibilityistobindmodeltoview.Modelcanbefetchedfromservice!–  Controllerisnotresponsibleformanipula6ng(create,destroy,update)thedata.UseServicesinstead!

•  AngularJShasmanybuilt---inservices,see–  hBp://docs.angularjs.org/api/ng/service–  Example:$http

Page 58: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

Services

ViewCustomers(htmlfragment)

ViewCustomersCtrl

$scope

Service

ModifyCustomers(htmlfragment)

ModifyCustomerCtrl

$scope

Page 59: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

AngularJSCustomServicesusingFactory

// Let's add a new controller to MyApp. This controller uses Service! myApp.controller('ViewCtrl', function ($scope, CustomerService) {

$scope.contacts = CustomerService.contacts; }); // Let's add a new controller to MyApp. This controller uses Service! myApp.controller('ModifyCtrl', function ($scope, CustomerService) {

$scope.contacts = CustomerService.contacts; }); // Creating a factory object that contains services for the // controllers. myApp.factory('CustomerService', function() {

var factory = {}; factory.contacts = [{name: "Jack", salary: 3000}, {name: "Tina",

salary: 5000}, {name: "John", salary: 4000}]; return factory;

});

Page 60: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

AlsoServiceis instantiated with new – keyword.

function can use "this" and the return

// Service

// Service // value is this. myApp.service('CustomerService', function()

{ this.contacts =

[{name: "Jack", salary: 3000},

{name: {name:

"Tina", "John",

salary: salary:

5000}, 4000}];

});

Page 61: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

AJAX+REST

Page 62: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

AJAX

•  AsynchronousJavaScript+XML– XMLnotneeded,veryodenJSON

•  Senddataandretrieveasynchronouslyfromserverinbackground

•  Groupoftechnologies– HTML,CSS,DOM,XML/JSON,XMLHBpRequestobjectandJavaScript

Page 63: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

$http –example(AJAX)andAngularJS

<script type="text/javascript"> var myapp = angular.module("myapp", []);

myapp.controller("MyController", function($scope, $http) {

$scope.myData = {}; $scope.myData.doClick = function(item, event) {

var responsePromise = $http.get("text.txt");

responsePromise.success(function(data, status, headers, config) {

$scope.myData.fromServer = data; });

responsePromise.error(function(data, status, headers, config) { alert("AJAX failed!");

});

} } );

</script>

Page 64: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

RESTful

•  WebServiceAPIsthatadheretoRESTarchitecturalconstrainsarecalledRESTful

•  Constrains– BaseURI,suchashBp://www.example/resources–  Internetmediatypefordata,suchasJSONorXML– StandardHTTPmethods:GET,POST,PUT,DELETE– Linkstoreferencereferencestateandrelatedresources

Page 65: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

RESTfulAPIHTTPmethods(wikipedia)

Page 66: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

AJAX+RESTful

•  ThewebappcanfetchusingRESTfuldatafromserver

•  UsingAJAXthisisdoneasynchronouslyinthebackground

•  AJAXmakesHTTPGETrequestusingurl..– hBp://example.com/resources/item17

•  ..andreceivesdataofitem17inJSON...•  ..whichcanbedisplayedinview(webpage)

Page 67: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

Example:WeatherAPI

•  Weatherinforma6onavailablefromwunderground.com

– Youhavetomakeaccountandreceiveakey

•  TogetHelsinkiweatherinJSON– http://api.wunderground.com/api/your-key/ conditions/q/Helsinki.json

Page 68: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

{

"response": { "version":

"0.1", "termsofService": "http:\/\/www.wunderground.com\/weather\/api\/d\/terms.html", "features":

{ "conditions"

: 1

}

}, "current_observation": { "image": {

"url": "http:\/\/icons.wxug.com\/graphics\/wu2\/logo_130x80.png",

"title": "Weather Underground",

"link": "http:\/\/www.wunderground.com"

},

"display_location": { "full": "Helsinki, Finland",

"city": "Helsinki",

"state": "",

"state_name": "Finland",

"country": "FI",

"country_iso3166": "FI",

"zip": "00000", "magic": "1",

"wmo": "02974",

"latitude": "60.31999969",

"longitude": "24.96999931",

"elevation": "56.00000000"

},

Page 69: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

<!DOCTYPE html> <html> <head> <script src="../angular.min.js" type="text/javascript"></script> <title></title>

</head> <body data-ng-app="myapp"> <div data-ng-controller="MyController"> <button data-ng-click="myData.doClick(item, $event)">Get Helsinki Weather</button><br /> Data from server: {{myData.fromServer}}

</div>

<script type="text/javascript"> var myapp = angular.module("myapp", []);

myapp.controller("MyController", function($scope, $http) { $scope.myData = {}; $scope.myData.doClick = function(item, event) {

var responsePromise = $http.get("http://api.wunderground.com/api/key/conditions/ q/Helsinki.json");

responsePromise.success(function(data, status, headers, config) { $scope.myData.fromServer = "" + data.current_observation.weather +

" " + data.current_observation.temp_c + " c"; }); responsePromise.error(function(data, status, headers, config) {

alert("AJAX failed!"); });

} } );

</script> </body> </html>

ThisisJSONobject!

Page 70: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

ViewawerpressingtheBuBon

Page 71: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

$resource

•  Builtontopof$hBpservice,$resourceisafactorythatletsyouinteractwithRESTfulbackendseasily

•  $resourcedoesnotcomebundledwithmainAngularscript,separatelydownload– angular-resource.min.js

•  YourmainappshoulddeclaredependencyonthengResourcemoduleinordertouse$resource

Page 72: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

GexngStartedwith$resource

•  $resourceexpectsclassicRESTfulbackend– http://en.wikipedia.org/wiki/ Representational_state_transfer#Applied_t o_web_services

•  Youcancreatethebackendbywhatevertechnology.EvenJavaScript,forexampleNode.js

•  Wearenotconcentra6ngnowhowtobuildthebackend.

Page 73: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

Using$resourceonGET// Load ngResource before this var restApp = angular.module('restApp',['ngResource']); restApp.controller("RestCtrl", function($scope, $resource) {

$scope.doClick = function() { var title = $scope.movietitle; var searchString = 'http://api.rottentomatoes.com/api/

public/v1.0/movies.json?apikey=key&q=' + title + '&page_limit=5';

var result = $resource(searchString);

// {method:'GET' var root = result.get(function() { $scope.movies = root.movies;

}); }

});

Page 74: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

$resourcemethods

•  $resourcecontainsconvenientmethodsfor– get ('GET') – save ('POST') – query ('GET', isArray:true) – remove ('DELETE')

•  Callingthesewillinvoke$hBp(ajaxcall)withthespecifiedhBpmethod(GET,POST,DELETE),des6na6onandparameters

Page 75: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

PassingParameters// Load ngResource before this var restApp = angular.module('restApp',['ngResource']);

restApp.controller("RestCtrl", function($scope, $resource) { $scope.doClick = function() {

var searchString = 'http://api.rottentomatoes.com/api/public/ v1.0/movies.json?apikey=key&q=:title&page_limit=5';

var result = $resource(searchString); var root = result.get({title: $scope.movietitle}, function() {

$scope.movies = root.movies;

});

}

});

:6tle--->parametrizedURLtemplate

Givingtheparameterfrom

$scope

Page 76: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

UsingServices// Load ngResource before this var restApp = angular.module('restApp',['ngResource']);

restApp.controller("RestCtrl", function($scope, MovieService) { $scope.doClick = function() {

var root = MovieService.resource.get({title: $scope.movietitle}, function() {

$scope.movies = root.movies; });

}

});

restApp.factory('MovieService', function($resource)

{ factory = {};

factory.resource = $resource('http://api.rottentomatoes...&q=:title&page_limit=5'); return factory;

});

Controllerresponsiblefor

binding

Serviceresponsiblefortheresource

Page 77: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

SimpleVersion// Load ngResource before this var restApp = angular.module('restApp',['ngResource']);

MovieService) {

$scope.movietitle},

restApp.controller("RestCtrl", function($scope, $scope.doClick = function() {

var root = MovieService.get({title: function() {

$scope.movies = root.movies;

}); }

});

restApp.factory('MovieService', function($resource) { return $resource('http://api.rottentomatoes...&q=:title&page_limit=5');;

});

JustcallgetfromMovieService

Returnstheresource

Page 78: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

ANIMATIONSANDUNITTESTING

Page 79: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

AngularJSAnima6ons

•  IncludengAnimatemoduleasdependency•  Hookanima6onsforcommondirec6vessuchasngRepeat,ngSwitch,ngView

•  BasedonCSSclasses– IfHTMLelementhasclass,youcananimateit

•  AngularJSaddsspecialclassestoyourhtml---elements

Page 80: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

ExampleForm<body ng-controller="AnimateCtrl"> <button ng-click="add()">Add</button> <button ng-click="remove()">Remove</button></p> <ul> <li ng-repeat="customer in

customers">{{customer.name}}</li> </ul>

</body>

AddsandRemovesnames

Page 81: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

Anima6onClasses

•  Whenaddinganewnametothemodel,ng---repeatknowstheitemthatiseitheraddedordeleted

•  CSSclassesareaddedatrun6metotherepeatedelement(<li>)

•  Whenaddingnewelement:–  <li class="... ng-enter ng-enter-active">New Name</li>

•  Whenremovingelement–  <li class="... ng-leave ng-leave-active">New Name</li>

Page 82: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

Direc6vesandCSSEvent Star7ngCSS EndingCSS Direc7ves

enter .ng---enter .ng---enter---ac6ve ngRepeat,ngInclude,ngIf,ngView

leave .ng---leave .ng---leave---ac6ve ngRepeat,ngInclude,ngIf,ngView

move .ng---move .ng---move.ac6ve ngRepeat

Page 83: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

ExampleCSS/* starting animation */ .ng-enter { -webkit-transition: 1s; transition: 1s;

margin-left: 100%; }

/* ending animation */

.ng-enter-active { margin-left: 0;

}

/* starting animation */

.ng-leave { -webkit-transition: 1s; transition: 1s;

margin-left: 0; }

/* ending animation */

.ng-leave-active {

margin-left: 100%; }

Page 84: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

TestDrivenDesign

•  Writetestsfirsts,thenyourcode•  AngularJSemphasizesmodularity,soitcanbeeasytotestyourcode

•  Codecanbetestedusingseveralunittes6ngframeworks,likeQUnit,Jasmine,Mocha...

Page 85: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

QUnit

•  Downloadqunit.js andqunit.css •  WriteasimpleHTMLpagetorunthetests•  Writethetests

Page 86: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

<!DOCTYPE html> <html> <head> <meta charset="utf-8">

<title>QUnit Example</title> <link rel="stylesheet" href="qunit-1.10.0.css"> <script src="qunit-1.10.0.js"></script>

</head> <body> <div id="qunit"></div> <script type="text/javascript">

function calculate(a, b) {

return a + b;

}

"Ok!"

"Ok!" "OK!"

"calculate test", function() { );

); );

test( ok( calculate(5,5) === 10,

ok( calculate(5,0) === 5, ok( calculate(-5,5) === 0,

});

</script> </body> </html>

Page 87: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

ThreeAsser6ons

•  Basic– ok( boolean [, message]);

•  Ifactual==expected– equal( actual, expected [, message]);

•  ifactual===expected– deepEqual( actual, expected [, message));

•  Other– http://qunitjs.com/cookbook/#automating- unit-testing

Page 88: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

Tes6ngAngularJSServicevar myApp = angular.module('myApp', []); // One service myApp.service('MyService', function() {

function(a, b) { a + b;

this.add = return

}; }); /* TESTS */ var injector = angular.injector(['ng', 'myApp']); QUnit.test('MyService', function() {

var MyService = injector.get('MyService'); ok(2 == MyService.add(1, 1));

});

Page 89: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

WRAPPINGUP

Page 90: Modified from a presentaon by Jussi Pohjolainenlatemar.science.unitn.it/.../AngularJS-Intro-1.pdf · 2017-12-20 · Angular JS • Single Page App Framework for JavaScript • Implements

WrappingUP

•  AngularJSisamodularJavaScriptSPAframework

•  Lotofgreatfeatures,butlearningcurvecanbehard

•  GreatforCRUD(create,read,update,delete)apps,butnotsuitableforeverytypeofapps

•  WorksverywellwithsomeJSlibraries(JQuery)