SlideShare a Scribd company logo
AngularJS Application
Routing
Tuesday, 13 August 13
Routes: REST/Servers v. Client Apps
•HTTP is stateless, so routes help define application state.
•REST emphasizes semantic routes. (GET	
  /user/dave)
But...
•There is more state than can be represented in a route (user
state, session state)
•Client-side apps don’t actually need routes to work (e.g. many
jquery-based apps)
Tuesday, 13 August 13
Why use routes?
Routes:
•Make the back button work as expected
•Make major (page-like) transitions clear
•Allow easy linking
•Make testing easier
•Encapsulate some state
Tuesday, 13 August 13
From Angular-Phonecat:
angular.module('phonecat',	
  ['phonecatFilters',	
  
'phonecatServices']).
	
  	
  config(['$routeProvider',	
  function($routeProvider)	
  {
	
  	
  $routeProvider.
	
  	
  	
  	
  	
  	
  when('/phones',	
  {templateUrl:	
  'partials/phone-­‐
list.html',	
  	
  	
  controller:	
  PhoneListCtrl}).
	
  	
  	
  	
  	
  	
  when('/phones/:phoneId',	
  {templateUrl:	
  'partials/
phone-­‐detail.html',	
  controller:	
  PhoneDetailCtrl}).
	
  	
  	
  	
  	
  	
  otherwise({redirectTo:	
  '/phones'});
}]);
Basic Routes
Tuesday, 13 August 13
.when('/phones/:phoneId',	
  {templateUrl:	
  'partials/phone-­‐
detail.html',	
  controller:	
  PhoneDetailCtrl})
:phoneId stored in $route.current.params, available
controller and resolve functions.
Basic Routes
Tuesday, 13 August 13
Realistic Routes Structure
/ – welcome
/stream – logged-in home
/login – log-in
/signup – signup
/user/:username – user profile
/explore – explore tags
/settings – user settings
/new-spark – create spark page
/spark/cluster?sparkName=&tagName – spark cluster page
/search – search
/spark/:username/:slug – spark page
...and 11 more routes
Tuesday, 13 August 13
Resolve for Data
Each item in the resolve map:
•Runs before the controller is instantiated
•Provides its value to the controller
•If it is a promise:
•It will (wait to) resolve the promise first
•If the promise is rejected, the route errors
Using resolve for database objects means
•No UI flicker as promises are resolved
•Controllers can assume objects exist
•Tests are cleaner: pass in data object explicitly
Tuesday, 13 August 13
Resolve for Data
when('/tag/:tagName',	
  {
	
  resolve:	
  {
	
  	
  tagResolve:	
  ['tag','$route',
	
  	
  	
  function	
  (tagService,	
  $route)	
  {
	
  	
  	
  	
  return	
  tagService.get($route.current.params.tagName);
	
  	
  }],
	
  	
  sparkClustersResolve:	
  ['sparkCluster','$route',
	
  	
  	
  function	
  (sparkClusterService,	
  $route)	
  {
	
  	
  	
  	
  return	
  
sparkClusterService.getSparkClustersByTag($route.current.p
arams.tagName);
}]}});
Tuesday, 13 August 13
Resolve for Data
Treat your resolved object like a dependency in the controller:
.controller('ViewTagCtrl',	
  ['$scope','$routeParams','tag',
'sparkCluster','log','$location','user','header','sparkClu
stersResolve','tagResolve','currentUserResolve'
Use a ‘route controller’, not a ‘view controller’ (ng-­‐controller):
when('/tag/:tagName',	
  {
	
  controller:	
  'ViewTagCtrl'	
  })
Tuesday, 13 August 13
Resolve for Rules
Rejected Promises cause routes to fail. You can use this to make
rules for the route like ACLs or prerequisites. Reject a promise to
cause a route to fail.
Using resolve to make rules means:
•All resolution rules must pass before route succeeds and
controller is instantiated.
•Common ACLs (logged-in) specified in routes, not each
controller or service
•Can redirect the user to an appropriate page (also can do
user-facing error)
Tuesday, 13 August 13
when('/tag/:tagName',	
  {
	
  resolve:	
  {
	
  	
  mustAuth	
  :	
  ['route',	
  function	
  (routeService)	
  {
	
  	
  	
  	
  return	
  routeService.mustAuth('/');}]}]}});
routeService.mustAuth	
  =	
  function	
  (redirectTo)	
  {
	
  var	
  authDeferred,	
  p;
	
  authDeferred	
  =	
  $q.defer();
	
  p	
  =	
  userService.getCurrent();
	
  p.then(function	
  (currentUser)	
  {
	
  	
  if	
  (angular.isUndefined(currentUser._id))	
  {
	
  	
  	
  $location.url(redirectTo);
	
  	
  	
  authDeferred.reject();
	
  	
  }	
  else	
  {	
  authDeferred.resolve(mustAuth);	
  }});
	
  return	
  authDeferred.promise;
};
Resolve for Rules
Tuesday, 13 August 13
Resolve for Route-Specific UI
Resolve can pass route-specific configuration to another service
that affects the UI, like “show a promo”.
Using resolve to control UI means:
•Routes handle turning on and off UI elements
•Route Controllers don’t need to worry about configuring site-
wide UI elements like headers, promos, menus
*There are other (possibly better) options for this, including
having the UI controller listen to RouteChangeSuccess events.
Tuesday, 13 August 13
when('/tag/:tagName',	
  {
	
  resolve:	
  {
	
  	
  makeSparkPromo:	
  ['promo',
	
  	
  	
  function	
  (promoService)	
  {
	
  	
  	
  	
  return	
  promoService.route('makeSparkPromo',	
  true);
}]}}});
Resolve for Route-Specific UI
Tuesday, 13 August 13
Testing Routes Midway
Normally you can only test routing with E2E testing, slowly.
Midway Testing (see Year Of Moo) is basically big unit testing.
Use a router helper, which has routeDefined, getRoute.
Midway testing routes means unittesting-like speed and E2E-like
app setup.
Tuesday, 13 August 13
ROUTER.when('tag',	
  '/tag/:tagName',	
  {
	
  templateUrl:	
  '/partials/tag/tag-­‐detail.html',
	
  controller:	
  'ViewTagCtrl'
});
ROUTER.otherwise({
	
  redirectTo	
  :	
  '/'
});
ROUTER.install($routeProvider);
Testing Routes Midway–Router Helper
Tuesday, 13 August 13
before(function(done)	
  {
	
  test	
  =	
  new	
  ngMidwayTester();
	
  test.register('App',	
  done);
});
it('should	
  have	
  a	
  route	
  to	
  a	
  tag	
  page',	
  function()	
  {
	
  	
  	
  	
  expect(	
  ROUTER.routeDefined('tags')).to.equal(true);
	
  var	
  url	
  =	
  ROUTER.routePath('tags',	
  {tagName:	
  ‘cooking’);
	
  expect(url).to.equal('/tag/cooking');
});
Testing Routes Midway–Testing
Tuesday, 13 August 13
Recap
The phonecat way (sticking everything under app) is unscalable.
Angular’s route system is flexible and powerful, if you take
advantage of resolve and promises.
Using helper functions and midway testing means you can unit
test more things. The less you rely on E2E testing, the better.
Tuesday, 13 August 13
Other Good Ideas
Others have addressed the same problems in a more reusable
way.
Angular UI router: use ‘state’ instead of routes. Seems good.
Worth considering if you start fresh.
Angular App: great example of well-designed app, but maybe
hard to follow for a novice. Interesting crudRouteProvider
implementation.
Tuesday, 13 August 13

More Related Content

What's hot

Angular js routing options
Angular js routing optionsAngular js routing options
Angular js routing optionsNir Kaufman
 
Building an End-to-End AngularJS Application
Building an End-to-End AngularJS ApplicationBuilding an End-to-End AngularJS Application
Building an End-to-End AngularJS ApplicationDan Wahlin
 
Dart and AngularDart
Dart and AngularDartDart and AngularDart
Dart and AngularDartLoc Nguyen
 
Binary Studio Academy 2016: Laravel Routing
Binary Studio Academy 2016: Laravel Routing Binary Studio Academy 2016: Laravel Routing
Binary Studio Academy 2016: Laravel Routing Binary Studio
 
Optimizing Angular Performance in Enterprise Single Page Apps
Optimizing Angular Performance in Enterprise Single Page AppsOptimizing Angular Performance in Enterprise Single Page Apps
Optimizing Angular Performance in Enterprise Single Page AppsMorgan Stone
 
Angular meetup - routing and multilingual urls
Angular meetup - routing and multilingual urlsAngular meetup - routing and multilingual urls
Angular meetup - routing and multilingual urlsSasha Vinčić
 
AngularJS - $http & $resource Services
AngularJS - $http & $resource ServicesAngularJS - $http & $resource Services
AngularJS - $http & $resource ServicesEyal Vardi
 
AngularJS Services
AngularJS ServicesAngularJS Services
AngularJS ServicesEyal Vardi
 
Comment pages 002
Comment pages 002Comment pages 002
Comment pages 002RiNi Ft
 
MEAN - Notes from the field (Full-Stack Development with Javascript)
MEAN - Notes from the field (Full-Stack Development with Javascript)MEAN - Notes from the field (Full-Stack Development with Javascript)
MEAN - Notes from the field (Full-Stack Development with Javascript)Chris Clarke
 
AngularJS $Provide Service
AngularJS $Provide ServiceAngularJS $Provide Service
AngularJS $Provide ServiceEyal Vardi
 
Intro to Ember.js
Intro to Ember.jsIntro to Ember.js
Intro to Ember.jsJay Phelps
 
Routing And Navigation
Routing And NavigationRouting And Navigation
Routing And NavigationEyal Vardi
 
Binary Studio Academy 2016: Laravel Controllers
Binary Studio Academy 2016: Laravel ControllersBinary Studio Academy 2016: Laravel Controllers
Binary Studio Academy 2016: Laravel ControllersBinary Studio
 

What's hot (20)

Angular js routing options
Angular js routing optionsAngular js routing options
Angular js routing options
 
Building an End-to-End AngularJS Application
Building an End-to-End AngularJS ApplicationBuilding an End-to-End AngularJS Application
Building an End-to-End AngularJS Application
 
Dart and AngularDart
Dart and AngularDartDart and AngularDart
Dart and AngularDart
 
AngularJS
AngularJSAngularJS
AngularJS
 
Binary Studio Academy 2016: Laravel Routing
Binary Studio Academy 2016: Laravel Routing Binary Studio Academy 2016: Laravel Routing
Binary Studio Academy 2016: Laravel Routing
 
Optimizing Angular Performance in Enterprise Single Page Apps
Optimizing Angular Performance in Enterprise Single Page AppsOptimizing Angular Performance in Enterprise Single Page Apps
Optimizing Angular Performance in Enterprise Single Page Apps
 
Angular meetup - routing and multilingual urls
Angular meetup - routing and multilingual urlsAngular meetup - routing and multilingual urls
Angular meetup - routing and multilingual urls
 
Rails3 asset-pipeline
Rails3 asset-pipelineRails3 asset-pipeline
Rails3 asset-pipeline
 
AngularJS - $http & $resource Services
AngularJS - $http & $resource ServicesAngularJS - $http & $resource Services
AngularJS - $http & $resource Services
 
AngularJS Services
AngularJS ServicesAngularJS Services
AngularJS Services
 
Comment pages 002
Comment pages 002Comment pages 002
Comment pages 002
 
Modular and Event-Driven JavaScript
Modular and Event-Driven JavaScriptModular and Event-Driven JavaScript
Modular and Event-Driven JavaScript
 
MEAN - Notes from the field (Full-Stack Development with Javascript)
MEAN - Notes from the field (Full-Stack Development with Javascript)MEAN - Notes from the field (Full-Stack Development with Javascript)
MEAN - Notes from the field (Full-Stack Development with Javascript)
 
Pengenalan blaast platform sdk
Pengenalan blaast platform sdkPengenalan blaast platform sdk
Pengenalan blaast platform sdk
 
AngularJS $Provide Service
AngularJS $Provide ServiceAngularJS $Provide Service
AngularJS $Provide Service
 
Intro to Ember.js
Intro to Ember.jsIntro to Ember.js
Intro to Ember.js
 
Routing And Navigation
Routing And NavigationRouting And Navigation
Routing And Navigation
 
Binary Studio Academy 2016: Laravel Controllers
Binary Studio Academy 2016: Laravel ControllersBinary Studio Academy 2016: Laravel Controllers
Binary Studio Academy 2016: Laravel Controllers
 
Intro to Ember.JS 2016
Intro to Ember.JS 2016Intro to Ember.JS 2016
Intro to Ember.JS 2016
 
RequireJS
RequireJSRequireJS
RequireJS
 

Viewers also liked

Angular js presentation at Datacom
Angular js presentation at DatacomAngular js presentation at Datacom
Angular js presentation at DatacomDavid Xi Peng Yang
 
Sms pro - bulk SMS sending software
Sms pro - bulk SMS sending softwareSms pro - bulk SMS sending software
Sms pro - bulk SMS sending softwareLive Tecnologies
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Developmentguestc8093a6
 
TDD - Test Driven Development
TDD - Test Driven DevelopmentTDD - Test Driven Development
TDD - Test Driven DevelopmentTung Nguyen Thanh
 
Building single page applications
Building single page applicationsBuilding single page applications
Building single page applicationsSC5.io
 
Single Page Application presentation
Single Page Application presentationSingle Page Application presentation
Single Page Application presentationJohn Staveley
 
Single Page Application (SPA) using AngularJS
Single Page Application (SPA) using AngularJSSingle Page Application (SPA) using AngularJS
Single Page Application (SPA) using AngularJSM R Rony
 
Test Driven Development (TDD)
Test Driven Development (TDD)Test Driven Development (TDD)
Test Driven Development (TDD)David Ehringer
 
29 Essential AngularJS Interview Questions
29 Essential AngularJS Interview Questions29 Essential AngularJS Interview Questions
29 Essential AngularJS Interview QuestionsArc & Codementor
 
2015 Upload Campaigns Calendar - SlideShare
2015 Upload Campaigns Calendar - SlideShare2015 Upload Campaigns Calendar - SlideShare
2015 Upload Campaigns Calendar - SlideShareSlideShare
 
What to Upload to SlideShare
What to Upload to SlideShareWhat to Upload to SlideShare
What to Upload to SlideShareSlideShare
 
How to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & TricksHow to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & TricksSlideShare
 
Getting Started With SlideShare
Getting Started With SlideShareGetting Started With SlideShare
Getting Started With SlideShareSlideShare
 

Viewers also liked (18)

Angular js presentation at Datacom
Angular js presentation at DatacomAngular js presentation at Datacom
Angular js presentation at Datacom
 
Story planner
Story plannerStory planner
Story planner
 
Web Config
Web ConfigWeb Config
Web Config
 
Práctica para writer
Práctica para writerPráctica para writer
Práctica para writer
 
Sms pro - bulk SMS sending software
Sms pro - bulk SMS sending softwareSms pro - bulk SMS sending software
Sms pro - bulk SMS sending software
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
TDD - Test Driven Development
TDD - Test Driven DevelopmentTDD - Test Driven Development
TDD - Test Driven Development
 
ASP .net MVC
ASP .net MVCASP .net MVC
ASP .net MVC
 
Building single page applications
Building single page applicationsBuilding single page applications
Building single page applications
 
Single Page Application presentation
Single Page Application presentationSingle Page Application presentation
Single Page Application presentation
 
Single Page Application (SPA) using AngularJS
Single Page Application (SPA) using AngularJSSingle Page Application (SPA) using AngularJS
Single Page Application (SPA) using AngularJS
 
MS-SQL SERVER ARCHITECTURE
MS-SQL SERVER ARCHITECTUREMS-SQL SERVER ARCHITECTURE
MS-SQL SERVER ARCHITECTURE
 
Test Driven Development (TDD)
Test Driven Development (TDD)Test Driven Development (TDD)
Test Driven Development (TDD)
 
29 Essential AngularJS Interview Questions
29 Essential AngularJS Interview Questions29 Essential AngularJS Interview Questions
29 Essential AngularJS Interview Questions
 
2015 Upload Campaigns Calendar - SlideShare
2015 Upload Campaigns Calendar - SlideShare2015 Upload Campaigns Calendar - SlideShare
2015 Upload Campaigns Calendar - SlideShare
 
What to Upload to SlideShare
What to Upload to SlideShareWhat to Upload to SlideShare
What to Upload to SlideShare
 
How to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & TricksHow to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & Tricks
 
Getting Started With SlideShare
Getting Started With SlideShareGetting Started With SlideShare
Getting Started With SlideShare
 

Similar to Angular JS Routing

Angular directive filter and routing
Angular directive filter and routingAngular directive filter and routing
Angular directive filter and routingjagriti srivastava
 
Integrating Angular js & three.js
Integrating Angular js & three.jsIntegrating Angular js & three.js
Integrating Angular js & three.jsJosh Staples
 
Dependency Injection @ AngularJS
Dependency Injection @ AngularJSDependency Injection @ AngularJS
Dependency Injection @ AngularJSRan Mizrahi
 
Introducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and serverIntroducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and serverSpike Brehm
 
OttawaJS: angular accessibility
OttawaJS: angular accessibilityOttawaJS: angular accessibility
OttawaJS: angular accessibilityDerek Featherstone
 
Good karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with KarmaGood karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with KarmaExoLeaders.com
 
Introduction to Angular js 2.0
Introduction to Angular js 2.0Introduction to Angular js 2.0
Introduction to Angular js 2.0Nagaraju Sangam
 
Codeigniter : Custom Routing - Manipulate Uri
Codeigniter : Custom Routing - Manipulate UriCodeigniter : Custom Routing - Manipulate Uri
Codeigniter : Custom Routing - Manipulate UriAbdul Malik Ikhsan
 
Testing ASP.net Web Applications using Ruby
Testing ASP.net Web Applications using RubyTesting ASP.net Web Applications using Ruby
Testing ASP.net Web Applications using RubyBen Hall
 
AngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
AngularJs Superheroic JavaScript MVW Framework Services by Miracle StudiosAngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
AngularJs Superheroic JavaScript MVW Framework Services by Miracle StudiosLearnimtactics
 
An introduction to Ember.js
An introduction to Ember.jsAn introduction to Ember.js
An introduction to Ember.jscodeofficer
 
AngularJS for Java Developers
AngularJS for Java DevelopersAngularJS for Java Developers
AngularJS for Java DevelopersLoc Nguyen
 
Angular training - Day 3 - custom directives, $http, $resource, setup with ye...
Angular training - Day 3 - custom directives, $http, $resource, setup with ye...Angular training - Day 3 - custom directives, $http, $resource, setup with ye...
Angular training - Day 3 - custom directives, $http, $resource, setup with ye...murtazahaveliwala
 
Beyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance JavascriptBeyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance Javascriptaglemann
 

Similar to Angular JS Routing (20)

Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2
 
Angular directive filter and routing
Angular directive filter and routingAngular directive filter and routing
Angular directive filter and routing
 
Meteor iron:router
Meteor iron:routerMeteor iron:router
Meteor iron:router
 
Integrating Angular js & three.js
Integrating Angular js & three.jsIntegrating Angular js & three.js
Integrating Angular js & three.js
 
Dependency Injection @ AngularJS
Dependency Injection @ AngularJSDependency Injection @ AngularJS
Dependency Injection @ AngularJS
 
Introducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and serverIntroducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and server
 
OttawaJS: angular accessibility
OttawaJS: angular accessibilityOttawaJS: angular accessibility
OttawaJS: angular accessibility
 
AngularJs-training
AngularJs-trainingAngularJs-training
AngularJs-training
 
Good karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with KarmaGood karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with Karma
 
Introduction to Angular js 2.0
Introduction to Angular js 2.0Introduction to Angular js 2.0
Introduction to Angular js 2.0
 
Codeigniter : Custom Routing - Manipulate Uri
Codeigniter : Custom Routing - Manipulate UriCodeigniter : Custom Routing - Manipulate Uri
Codeigniter : Custom Routing - Manipulate Uri
 
Angular routing
Angular routingAngular routing
Angular routing
 
Testing ASP.net Web Applications using Ruby
Testing ASP.net Web Applications using RubyTesting ASP.net Web Applications using Ruby
Testing ASP.net Web Applications using Ruby
 
AngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
AngularJs Superheroic JavaScript MVW Framework Services by Miracle StudiosAngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
AngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
 
An introduction to Ember.js
An introduction to Ember.jsAn introduction to Ember.js
An introduction to Ember.js
 
Node.js server-side rendering
Node.js server-side renderingNode.js server-side rendering
Node.js server-side rendering
 
AngularJS for Java Developers
AngularJS for Java DevelopersAngularJS for Java Developers
AngularJS for Java Developers
 
Angular training - Day 3 - custom directives, $http, $resource, setup with ye...
Angular training - Day 3 - custom directives, $http, $resource, setup with ye...Angular training - Day 3 - custom directives, $http, $resource, setup with ye...
Angular training - Day 3 - custom directives, $http, $resource, setup with ye...
 
Beyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance JavascriptBeyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance Javascript
 
AngularJs
AngularJsAngularJs
AngularJs
 

Recently uploaded

Taurus Zodiac Sign_ Personality Traits and Sign Dates.pptx
Taurus Zodiac Sign_ Personality Traits and Sign Dates.pptxTaurus Zodiac Sign_ Personality Traits and Sign Dates.pptx
Taurus Zodiac Sign_ Personality Traits and Sign Dates.pptxmy Pandit
 
Lookback Analysis
Lookback AnalysisLookback Analysis
Lookback AnalysisSafe PaaS
 
BeMetals Presentation_May_22_2024 .pdf
BeMetals Presentation_May_22_2024   .pdfBeMetals Presentation_May_22_2024   .pdf
BeMetals Presentation_May_22_2024 .pdfDerekIwanaka1
 
G-Mica Wood Chip Particle board Table Design
G-Mica Wood Chip Particle board Table DesignG-Mica Wood Chip Particle board Table Design
G-Mica Wood Chip Particle board Table Designgmicaprelamdigital
 
Pitch Deck Teardown: RAW Dating App's $3M Angel deck
Pitch Deck Teardown: RAW Dating App's $3M Angel deckPitch Deck Teardown: RAW Dating App's $3M Angel deck
Pitch Deck Teardown: RAW Dating App's $3M Angel deckHajeJanKamps
 
Improving profitability for small business
Improving profitability for small businessImproving profitability for small business
Improving profitability for small businessBen Wann
 
Business Valuation Principles for Entrepreneurs
Business Valuation Principles for EntrepreneursBusiness Valuation Principles for Entrepreneurs
Business Valuation Principles for EntrepreneursBen Wann
 
New Product Development.kjiy7ggbfdsddggo9lo
New Product Development.kjiy7ggbfdsddggo9loNew Product Development.kjiy7ggbfdsddggo9lo
New Product Development.kjiy7ggbfdsddggo9logalbokkahewagenitash
 
NewBase 24 May 2024 Energy News issue - 1727 by Khaled Al Awadi_compresse...
NewBase   24 May  2024  Energy News issue - 1727 by Khaled Al Awadi_compresse...NewBase   24 May  2024  Energy News issue - 1727 by Khaled Al Awadi_compresse...
NewBase 24 May 2024 Energy News issue - 1727 by Khaled Al Awadi_compresse...Khaled Al Awadi
 
Strategy Analysis and Selecting ( Space Matrix)
Strategy Analysis and Selecting ( Space Matrix)Strategy Analysis and Selecting ( Space Matrix)
Strategy Analysis and Selecting ( Space Matrix)RidaKhan334971
 
April 2024 Nostalgia Products Newsletter
April 2024 Nostalgia Products NewsletterApril 2024 Nostalgia Products Newsletter
April 2024 Nostalgia Products NewsletterNathanBaughman3
 
IPTV Subscription UK: Your Guide to Choosing the Best Service
IPTV Subscription UK: Your Guide to Choosing the Best ServiceIPTV Subscription UK: Your Guide to Choosing the Best Service
IPTV Subscription UK: Your Guide to Choosing the Best ServiceDragon Dream Bar
 
Affordable Stationery Printing Services in Jaipur | Navpack n Print
Affordable Stationery Printing Services in Jaipur | Navpack n PrintAffordable Stationery Printing Services in Jaipur | Navpack n Print
Affordable Stationery Printing Services in Jaipur | Navpack n PrintNavpack & Print
 
Digital Transformation in PLM - WHAT and HOW - for distribution.pdf
Digital Transformation in PLM - WHAT and HOW - for distribution.pdfDigital Transformation in PLM - WHAT and HOW - for distribution.pdf
Digital Transformation in PLM - WHAT and HOW - for distribution.pdfJos Voskuil
 
5 Things You Need To Know Before Hiring a Videographer
5 Things You Need To Know Before Hiring a Videographer5 Things You Need To Know Before Hiring a Videographer
5 Things You Need To Know Before Hiring a Videographerofm712785
 
Transforming Max Life Insurance with PMaps Job-Fit Assessments- Case Study
Transforming Max Life Insurance with PMaps Job-Fit Assessments- Case StudyTransforming Max Life Insurance with PMaps Job-Fit Assessments- Case Study
Transforming Max Life Insurance with PMaps Job-Fit Assessments- Case StudyPMaps Assessments
 
anas about venice for grade 6f about venice
anas about venice for grade 6f about veniceanas about venice for grade 6f about venice
anas about venice for grade 6f about veniceanasabutalha2013
 
IPTV Subscription in Ireland: Elevating Your Entertainment Experience
IPTV Subscription in Ireland: Elevating Your Entertainment ExperienceIPTV Subscription in Ireland: Elevating Your Entertainment Experience
IPTV Subscription in Ireland: Elevating Your Entertainment ExperienceDragon Dream Bar
 

Recently uploaded (20)

Taurus Zodiac Sign_ Personality Traits and Sign Dates.pptx
Taurus Zodiac Sign_ Personality Traits and Sign Dates.pptxTaurus Zodiac Sign_ Personality Traits and Sign Dates.pptx
Taurus Zodiac Sign_ Personality Traits and Sign Dates.pptx
 
Lookback Analysis
Lookback AnalysisLookback Analysis
Lookback Analysis
 
BeMetals Presentation_May_22_2024 .pdf
BeMetals Presentation_May_22_2024   .pdfBeMetals Presentation_May_22_2024   .pdf
BeMetals Presentation_May_22_2024 .pdf
 
G-Mica Wood Chip Particle board Table Design
G-Mica Wood Chip Particle board Table DesignG-Mica Wood Chip Particle board Table Design
G-Mica Wood Chip Particle board Table Design
 
Pitch Deck Teardown: RAW Dating App's $3M Angel deck
Pitch Deck Teardown: RAW Dating App's $3M Angel deckPitch Deck Teardown: RAW Dating App's $3M Angel deck
Pitch Deck Teardown: RAW Dating App's $3M Angel deck
 
Improving profitability for small business
Improving profitability for small businessImproving profitability for small business
Improving profitability for small business
 
Business Valuation Principles for Entrepreneurs
Business Valuation Principles for EntrepreneursBusiness Valuation Principles for Entrepreneurs
Business Valuation Principles for Entrepreneurs
 
New Product Development.kjiy7ggbfdsddggo9lo
New Product Development.kjiy7ggbfdsddggo9loNew Product Development.kjiy7ggbfdsddggo9lo
New Product Development.kjiy7ggbfdsddggo9lo
 
NewBase 24 May 2024 Energy News issue - 1727 by Khaled Al Awadi_compresse...
NewBase   24 May  2024  Energy News issue - 1727 by Khaled Al Awadi_compresse...NewBase   24 May  2024  Energy News issue - 1727 by Khaled Al Awadi_compresse...
NewBase 24 May 2024 Energy News issue - 1727 by Khaled Al Awadi_compresse...
 
Strategy Analysis and Selecting ( Space Matrix)
Strategy Analysis and Selecting ( Space Matrix)Strategy Analysis and Selecting ( Space Matrix)
Strategy Analysis and Selecting ( Space Matrix)
 
April 2024 Nostalgia Products Newsletter
April 2024 Nostalgia Products NewsletterApril 2024 Nostalgia Products Newsletter
April 2024 Nostalgia Products Newsletter
 
Sustainability: Balancing the Environment, Equity & Economy
Sustainability: Balancing the Environment, Equity & EconomySustainability: Balancing the Environment, Equity & Economy
Sustainability: Balancing the Environment, Equity & Economy
 
IPTV Subscription UK: Your Guide to Choosing the Best Service
IPTV Subscription UK: Your Guide to Choosing the Best ServiceIPTV Subscription UK: Your Guide to Choosing the Best Service
IPTV Subscription UK: Your Guide to Choosing the Best Service
 
Affordable Stationery Printing Services in Jaipur | Navpack n Print
Affordable Stationery Printing Services in Jaipur | Navpack n PrintAffordable Stationery Printing Services in Jaipur | Navpack n Print
Affordable Stationery Printing Services in Jaipur | Navpack n Print
 
Communicative rationality and the evolution of business ethics: corporate soc...
Communicative rationality and the evolution of business ethics: corporate soc...Communicative rationality and the evolution of business ethics: corporate soc...
Communicative rationality and the evolution of business ethics: corporate soc...
 
Digital Transformation in PLM - WHAT and HOW - for distribution.pdf
Digital Transformation in PLM - WHAT and HOW - for distribution.pdfDigital Transformation in PLM - WHAT and HOW - for distribution.pdf
Digital Transformation in PLM - WHAT and HOW - for distribution.pdf
 
5 Things You Need To Know Before Hiring a Videographer
5 Things You Need To Know Before Hiring a Videographer5 Things You Need To Know Before Hiring a Videographer
5 Things You Need To Know Before Hiring a Videographer
 
Transforming Max Life Insurance with PMaps Job-Fit Assessments- Case Study
Transforming Max Life Insurance with PMaps Job-Fit Assessments- Case StudyTransforming Max Life Insurance with PMaps Job-Fit Assessments- Case Study
Transforming Max Life Insurance with PMaps Job-Fit Assessments- Case Study
 
anas about venice for grade 6f about venice
anas about venice for grade 6f about veniceanas about venice for grade 6f about venice
anas about venice for grade 6f about venice
 
IPTV Subscription in Ireland: Elevating Your Entertainment Experience
IPTV Subscription in Ireland: Elevating Your Entertainment ExperienceIPTV Subscription in Ireland: Elevating Your Entertainment Experience
IPTV Subscription in Ireland: Elevating Your Entertainment Experience
 

Angular JS Routing

  • 2. Routes: REST/Servers v. Client Apps •HTTP is stateless, so routes help define application state. •REST emphasizes semantic routes. (GET  /user/dave) But... •There is more state than can be represented in a route (user state, session state) •Client-side apps don’t actually need routes to work (e.g. many jquery-based apps) Tuesday, 13 August 13
  • 3. Why use routes? Routes: •Make the back button work as expected •Make major (page-like) transitions clear •Allow easy linking •Make testing easier •Encapsulate some state Tuesday, 13 August 13
  • 4. From Angular-Phonecat: angular.module('phonecat',  ['phonecatFilters',   'phonecatServices']).    config(['$routeProvider',  function($routeProvider)  {    $routeProvider.            when('/phones',  {templateUrl:  'partials/phone-­‐ list.html',      controller:  PhoneListCtrl}).            when('/phones/:phoneId',  {templateUrl:  'partials/ phone-­‐detail.html',  controller:  PhoneDetailCtrl}).            otherwise({redirectTo:  '/phones'}); }]); Basic Routes Tuesday, 13 August 13
  • 5. .when('/phones/:phoneId',  {templateUrl:  'partials/phone-­‐ detail.html',  controller:  PhoneDetailCtrl}) :phoneId stored in $route.current.params, available controller and resolve functions. Basic Routes Tuesday, 13 August 13
  • 6. Realistic Routes Structure / – welcome /stream – logged-in home /login – log-in /signup – signup /user/:username – user profile /explore – explore tags /settings – user settings /new-spark – create spark page /spark/cluster?sparkName=&tagName – spark cluster page /search – search /spark/:username/:slug – spark page ...and 11 more routes Tuesday, 13 August 13
  • 7. Resolve for Data Each item in the resolve map: •Runs before the controller is instantiated •Provides its value to the controller •If it is a promise: •It will (wait to) resolve the promise first •If the promise is rejected, the route errors Using resolve for database objects means •No UI flicker as promises are resolved •Controllers can assume objects exist •Tests are cleaner: pass in data object explicitly Tuesday, 13 August 13
  • 8. Resolve for Data when('/tag/:tagName',  {  resolve:  {    tagResolve:  ['tag','$route',      function  (tagService,  $route)  {        return  tagService.get($route.current.params.tagName);    }],    sparkClustersResolve:  ['sparkCluster','$route',      function  (sparkClusterService,  $route)  {        return   sparkClusterService.getSparkClustersByTag($route.current.p arams.tagName); }]}}); Tuesday, 13 August 13
  • 9. Resolve for Data Treat your resolved object like a dependency in the controller: .controller('ViewTagCtrl',  ['$scope','$routeParams','tag', 'sparkCluster','log','$location','user','header','sparkClu stersResolve','tagResolve','currentUserResolve' Use a ‘route controller’, not a ‘view controller’ (ng-­‐controller): when('/tag/:tagName',  {  controller:  'ViewTagCtrl'  }) Tuesday, 13 August 13
  • 10. Resolve for Rules Rejected Promises cause routes to fail. You can use this to make rules for the route like ACLs or prerequisites. Reject a promise to cause a route to fail. Using resolve to make rules means: •All resolution rules must pass before route succeeds and controller is instantiated. •Common ACLs (logged-in) specified in routes, not each controller or service •Can redirect the user to an appropriate page (also can do user-facing error) Tuesday, 13 August 13
  • 11. when('/tag/:tagName',  {  resolve:  {    mustAuth  :  ['route',  function  (routeService)  {        return  routeService.mustAuth('/');}]}]}}); routeService.mustAuth  =  function  (redirectTo)  {  var  authDeferred,  p;  authDeferred  =  $q.defer();  p  =  userService.getCurrent();  p.then(function  (currentUser)  {    if  (angular.isUndefined(currentUser._id))  {      $location.url(redirectTo);      authDeferred.reject();    }  else  {  authDeferred.resolve(mustAuth);  }});  return  authDeferred.promise; }; Resolve for Rules Tuesday, 13 August 13
  • 12. Resolve for Route-Specific UI Resolve can pass route-specific configuration to another service that affects the UI, like “show a promo”. Using resolve to control UI means: •Routes handle turning on and off UI elements •Route Controllers don’t need to worry about configuring site- wide UI elements like headers, promos, menus *There are other (possibly better) options for this, including having the UI controller listen to RouteChangeSuccess events. Tuesday, 13 August 13
  • 13. when('/tag/:tagName',  {  resolve:  {    makeSparkPromo:  ['promo',      function  (promoService)  {        return  promoService.route('makeSparkPromo',  true); }]}}}); Resolve for Route-Specific UI Tuesday, 13 August 13
  • 14. Testing Routes Midway Normally you can only test routing with E2E testing, slowly. Midway Testing (see Year Of Moo) is basically big unit testing. Use a router helper, which has routeDefined, getRoute. Midway testing routes means unittesting-like speed and E2E-like app setup. Tuesday, 13 August 13
  • 15. ROUTER.when('tag',  '/tag/:tagName',  {  templateUrl:  '/partials/tag/tag-­‐detail.html',  controller:  'ViewTagCtrl' }); ROUTER.otherwise({  redirectTo  :  '/' }); ROUTER.install($routeProvider); Testing Routes Midway–Router Helper Tuesday, 13 August 13
  • 16. before(function(done)  {  test  =  new  ngMidwayTester();  test.register('App',  done); }); it('should  have  a  route  to  a  tag  page',  function()  {        expect(  ROUTER.routeDefined('tags')).to.equal(true);  var  url  =  ROUTER.routePath('tags',  {tagName:  ‘cooking’);  expect(url).to.equal('/tag/cooking'); }); Testing Routes Midway–Testing Tuesday, 13 August 13
  • 17. Recap The phonecat way (sticking everything under app) is unscalable. Angular’s route system is flexible and powerful, if you take advantage of resolve and promises. Using helper functions and midway testing means you can unit test more things. The less you rely on E2E testing, the better. Tuesday, 13 August 13
  • 18. Other Good Ideas Others have addressed the same problems in a more reusable way. Angular UI router: use ‘state’ instead of routes. Seems good. Worth considering if you start fresh. Angular App: great example of well-designed app, but maybe hard to follow for a novice. Interesting crudRouteProvider implementation. Tuesday, 13 August 13