2. 2
Today…
• Single Page Applications – What / Why / How ?
• Brief Introduction to Angular JS aspects.,
• Discuss Code – https://github.com/ganeshkondal/angularstore
• Not Today
• Unit testing JavaScript Client side applications – see karma
• Node Server backend used
• Web Application or JavaScript basics
• Comparison across JS MVW frameworks
“Feel free to interrupt and also to provide feedback”
3. 3
Why SPA? Why now?
Technology Forecast &
the market is moving
towards it. Plus ‘not
just air’ – interesting
and its worth it
4. 4
What is it?
“is a web application or web site that fits on a
single web page with the goal of providing a more
fluid user experience akin to a desktop application”
–Wikipedia
5. 5
Single Page Application
• Web Apps not just web sites.
• Does not reload the page.
• Now driven with Javascript MVW frameworks
• Fluid UX Experience –
• Handles most of UI transactions in the client side.
• Loads majority of the code with a single page load
Timeline
…
6. 6
Why SPA?
“Within the time taken to read a page, 35 million person minutes
will be spent waiting for traditional website pages to load “ –
Single Page Applications [Upcoming SPA book of O’Reilly]
• Traditional Websites are slow !!!
• Slow site – is costly to enterprise & drives the customer away
• Mostly done using MVC – page after page delivery
• Does not provide a fluid UX – HTML is not for dynamic views
• Another reason – static content gets served to dumb clients
• SPA is to deliver a desktop application experience to the user
• And SPA is not new
7. 7
Why JS MVC?
• No Plugin / Less Bloat / One client language.
• jQuery is to manipulate DOM; for animation; hooking events
• Pain points – if jQuery is “all we have’
• State of the application is in DOM
• Logic and Presentation – “No separation of concerns”
• With more complicated flow – jQuery only code is
unmanageable / not modular
• Changes to features (UI or logic) in a large jQuery based
codebase ends in “Houston !!! We have a problem”
8. 8
Are we the guinea pigs?
• YouTube PS3
• Airbnb
• Google
• Maps
• Calendar
• Mail
• …
No Way?
http://builtwith.angularjs.org/
9. 9
SPA Frameworks
• Backbone JS
• Backbone. Marionette
• Angular JS – from Google
• Ember JS
• … many more
• See http://todomvc.com
10. 10
Didn’t we say ‘Responsive’
“ web design approach aimed at crafting sites to provide an optimal viewing
experience—easy reading and navigation with a minimum of resizing, panning,
and scrolling—across a wide range of devices” - Wikipedia
• Grid positioning and element sizing in % and relative numbers
• Flexible images
• CSS3 media queries
• CSS3 RWD frameworks
• Responsivator
11. Enterprise Application
- SPA with JS MVC
Presentation Layer
Model View Controller
11
SPA Architecture
Enterprise Application
- Using traditional
MVC approach
Presentation Layer
Services Tier
Data Access Layer
Database
Config
Files
Ext
Systems
13. 13
Why
• Angular is a MVVM / MVW framework; uses jQuery internally
• Some of the key features…
• Two-way data binding
• Dependency Injection
• HTML directives
• Reusable Services
• Custom Directives
• And a lot more…
• HTML 5 Routing
• HTML Templates
• Locale aware Filters
• Validation
• Nested form submission
• Expressions
+ Developed by / support from Google
14. 14
Trivia
• Started by Google in 2009; Open Source
• Saw a 17000 to 1500 line reduction of code (92% reduction in code)
• 100% JavaScript & Client Side. Compatible with desktop & mobile.
• Not a plugin; nor a browser extension
• Compatible with HTTPS, Content Security Policy, XSRF protection.,
• Done via $http with server [xsrf-token; settingx-xsrf-token]
• Browsers – Safari, Chrome, IE8/9, Firefox, Opera;
– Mobile browsers (Android, Chrome Mobile, Safari)
• Size < 29Kb (compressed and minified)
• Uses jQuery or jQlite
15. 15
Tool Sets
• Editor
• Sublime Text 2 Editor – tons of plugins
• $$ - Visual Studio or WebStorm IDE
• For Debugging –
• Chrome Browser
• Batarang [Angular JS plugin]
• Advanced REST Client OR Postman like Chrome / Firefox Plugin
• Firefox + firebug / jsFiddle …
• Library
• Bootstrap – CSS Framework
• Node Server (or Tomcat or IIS or Apache to host the pages)
16. 16
Tool Sets contd.
• Angular Seed Project –
• https://github.com/angular/angular-seed
• Responsivator
• http://dfcb.github.io/Responsivator/?site=localhos
t%3A8082%2Fbooks
• To check multi-modality in one shot
• Responsinator – iphone like online
simulator
• http://www.responsinator.com/
17. 17
Package Layout
UX code.
Reusable Services
Partial Views.
HTML Templates
SPA Entry Point
Controllers
(/controllers to be created)
Angular Seed – can provide the starting point
18. 18
Sample # 1 – Hello World
• ng-app, ng-init;
• Go through directives, before Sample 2
19. 19
Directives – HTML on steroids!!
• Directives teaches HTML new tricks [Dan Wahlin] by extending
HTML via attributes.
• ng-* - built in angular directives
• ng-app => Initializes the angular app.
• Built-in & Custom – directives
• Can be invoked as –
<span ng:bind="name"> ganesh
<span ng_bind="name"> ganesh
<span ng-bind="name"> ganesh
<span data-ng-bind="name"> ganesh
<span x-ng-bind="name"> ganesh `
21. 21
Sample 2 – Simple Data Binding
• Showcases view / model being tied.
• ng-bind
22. 22
Model
• Any JS object can be the model
• No special class to extend
• Unlike Backbone.Model.extend )
• No special template code.
• Angular works directly on the
DOM; so any HTML subset can be
the template.
View
25. 25
Controller
• Code behind the view
• Tied via the $scope
• $scope separates view
and the controller
• Controller is pure JS.
• No rendering info.
• Can support many views as it is not tied to a view
• Controller and View get the variables via DI of angular
26. 26
Filters & Expressions
• In-built filters are available
• to modify the output - $number
No fractions: {{ val | number : 0 } } <br/>
• to change the format $currency
• sort the returned data set orderBy: filter.name
• filter the data set, as the name says filter : filter.name
• For debugging
• Json filter is given in angular that prints in JSON style –
useful for debugging
<body> <pre>{{ {‘name’ : ‘value’} | json }} </pre> </body>
27. 27
$scope
• Glue between controller & view
• Refers the application model
• Scopes are in a hierarchical manner
• Helps create ($broadcast) custom events
$watch
# ng-model
# ng-change
<div
ng-controller="Controller">
Name:
<input type="text" ng-
model=‚name">
<button ng-
click='sayHello()'>greet</but
ton>
<hr>
{{greeting}}
$scope directives
• Expressions’ execution context
• Provides API to observe, propagate
model changes outside – via $watch,
$apply
View
Linking
phase
31. 31
Dependency Injection
• DI is pervasive – all over Angular.
• Controller gets hold of services it needs, auto-magically.
• View gets the necessary expression values.
• Each Angular application has $injector that injects the
dependent services (FYI only).
32. 32
Pieces Together - Modules
Modules
Controllers
Directives Filters
Service
Factory
Provider
Config
Routes
View
Value
• Modules are the containers => think like ‘object containers’
• Always use ng-app=‚moduleName‛
$scope
33. 33
Services
• Refers a common piece of code that you can use across
controllers. Not necessarily a REST or backend service call.
• Services are singleton apps
• Register a service – via .factory( serviceId, function(){..});
• OR via $provider interface.
• Always lazy initialized by Angular internally
34. 34
Security – HTML Injection
• HTML injection from unknown source is the HOLE
• Default behavior = print the HTML content in variable as is
• ngSanitize provides methods
• ng-bind-html – enables to get the text portion
• ng-bind-html-unsafe – enables even allowing the styling
portion along with the HTML content honored as is.
@html
@controller
35. 35
Next Session
• Integrate with Node JS or any REST service provider
• Organize / build code with Yeoman / Grunt (TODO list !!!)
• Test suite with Karma (ToDo list!!!)
• Custom Directives
36. 36
Summary
- SPA – what is it & why we need it
- Angular JS - what is it & some trivia
- Few code samples
- Key take away from Angular
- Dependency Injection
- Directives
- Routers
37. 37
Reference
- Angular JS – O’Reilly book
- http://angularjs.org
- www.youtube.com – Dan Wahlin’s video tutorials
41. 41
Angular JS Runtime
• Hello Angular Sample !!!
• Angular script loaded
• Ng-app designates the
application boundary
• Ng-repeat Sample !!!
• Info on Controllers
42. 42
SPA – FAQ
• What is dependency injected
• How it compares to backbone?
• How it compares to ember?
• What is the value model?
• Best Practices
• Upcoming; yet to settle in
Notes de l'éditeur
Anyone asking about jQuery.extend?
Anyone asking about jQuery.extend?
Cross Site Request Forgery (XSRF) Protection XSRF is a technique by which an unauthorized site can gain your user's private data. Angular provides following mechanism to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie called XSRF-TOKEN and sets it as the HTTP header X-XSRF-TOKEN. Since only JavaScript that runs on your domain could read the cookie, your server can be assured that the XHR came from JavaScript running on your domain.To take advantage of this, your server needs to set a token in a JavaScript readable session cookie called XSRF-TOKEN on first HTTP GET request. On subsequent non-GET requests the server can verify that the cookie matches X-XSRF-TOKEN HTTP header, and therefore be sure that only JavaScript running on your domain could have read the token. The token must be unique for each user and must be verifiable by the server (to prevent the JavaScript making up its own tokens). We recommend that the token is a digest of your site's authentication cookie with salt for added security.