Getting Started with Backbone.js Routes – Part IV: Configuring an Initialization Function

Backbone

Backbone.js LogoLearn how to configure a function that initializes your Backbone.js router

In the last few articles of this series, we have learned the basics of setting up routes in Backbone.js. We’ve discussed setting up route handlers, specifying a default route, graceful actions for corner-cases, as well as passing parameters to routes. But what about setup tasks? Sometimes you may want to execute code in preparation for your routes, but these tasks need to be completed before the routes are activated.

In this article, we will learn how to set up an initialization function that will run once, and is guaranteed to do so before the router is started.

Like much of what we have already discussed with regards to Backbone, this functionality is fairly straightforward. In the object that we pass to the Backbone.Router.Extend method, we provide an “initialize” property, which will be a method.

NOTE: In the code examples that follow, I have removed most of the implementation code so that the example will be shorter and easier to follow.

Example # 1

In Example # 1, we have added a property that is passed-into the Backbone.Route.extend method. This property is named: “initialize” and it is a method. This method will execute before the router is started. In this example, we simply fade-in a message, letting the user know that the router is initialized.

HERE IS WORKING CODE LINK FOR EXAMPLE # 1:

http://examples.kevinchisholm.com/backbone/routes/basics/html/part-iv-ex1.html

Example # 2

In Example # 2, we’ve upgraded our initialize method a bit. First, we moved all of the initialization code to the function: domSetup, just to keep the example code short and simple. There is no need to discuss the domSetup function in detail; it simply fades-in a message and sets up a few click handlers.

What interests us is the functionality that is provided here. Notice that when the page loads, if you click any of the nav links, nothing happens. This is because the router has not not been started yet. I have set a five-second timeout that delays the router’s start (the AJAX loader gif is spinning during this timeout). Once you see the green message fade-in, then all of the nav element clicks will work.

The point here was to demonstrate that if you have tasks you’d like to complete before the router is started, you can safely queue them up inside of the “initialize” method.

HERE IS WORKING CODE LINK FOR EXAMPLE # 2: http://examples.kevinchisholm.com/backbone/routes/basics/html/part-iv-ex2.html

How to Demo:

When the page loads, notice that there is an AJAX loader gif. As long as you see that AJAX loader, none of the nav element links work. Once the AJAX loader goes away and the message in a green box fades in, the nav links will work as expected. What is being demonstrated here is the fact that you can execute any setup code from the “initialize” method and then start the router manually as you wish. This is accomplished in the example code by placing all of the code that sets up the delay in the “initialize” method.

Summary

In this article, we learned how to set up an initialization function for a Backbone.js router. We learned about the “initialize” property of the object that we pass into Backbone.Router.extend, as well as how to manually start the router once our setup tasks have completed.

Getting Started with Backbone.js Routes – Part III: Passing Parameters to the Route

Backbone

Backbone.js LogoLearn how to pass values to your Backbone router in the URL

In the second part of this series: Getting Started with Backbone.js Routes – Part II: Handling Bad Requests, we learned how to handle route requests that are not configured in our router. This allows us complete control over the user experience, even when the request is one we had not anticipated. But what about parameters? How can we send the router a message? In other words, how can we pass a value in the URL that tells the application something specific?

In this article, we will learn how to pass parameters to the router, and in turn, how to access the values that are passed-in. So, for the examples that follow, we’ll imagine a very simple “order” page which allows you to specify the item you want to order in the URL. In order to keep the examples brief, I have removed any code that is not germane to the current discussion. But the full JS source code URL will be provided with each link to the working demo.

Example # 1

In Example # 1, we’ve set up a route named: “order/:item”. Up until now, our route names have been a single or hyphen-separated word. This new syntax, however, allows for more functionality.

Notice that in the route’s name, there is a colon. That colon tells Backbone that what follows is a parameter. So in this case, the actual route is “order/” and “:item” is a placeholder for whatever the user provides in that part of the URL. That value is an unknown, so we use the word “item” to represent this unknown value.

This route is handled by the method: “route”. Notice that the “route” method takes one argument: “item” (we could have named it anything, but I used “item” just to keep things consistent). This represents the parameter that was provided in the URL. So, inside of the “order” method, we now have access to that parameter.

HERE IS THE WORKING DEMO LINK FOR EXAMPLE # 1: http://examples.kevinchisholm.com/backbone/routes/basics/html/part-iii-ex1.html

HERE IS THE LINK FOR EXAMPLE # 1’s JavaScript: http://examples.kevinchisholm.com/backbone/routes/basics/js/part-iii-ex1.js

How to Demo:

Below the main nav is a brown navigation menu. As you click each menu item, notice that the URL changes. For example: “#/order/chair” or “#/order/shirt”. So, with each click, the message in the page will reflect the parameter passed in the URL after “#/order/”. You can enter whatever you like after “#/order/”, and that value will be reflected in the page’s message.

But what if the user wants to order more than one item?

Yes! This is a very logical feature to implement. It is common to specify a quantity when you order something. So, we’ll need to adjust our router so that the user can also provide the quantity in the URL in addition to the item name.

Example # 2

In Example # 2, we’ve added a new route: “order/:item/:count”. This route is also handled by the “order” method. There are two changes. This new route allows for a “count” parameter (i.e. “:count/”), and the “order” method takes a second argument: “count”.

Inside of the “order” method, we have updated the message that is injected into the DOM to include the “count” parameter, or the quantity of items to be ordered.

HERE IS THE WORKING DEMO LINK FOR EXAMPLE # 2:

http://examples.kevinchisholm.com/backbone/routes/basics/html/part-iii-ex2.html

HERE IS THE LINK FOR EXAMPLE # 1’s JavaScript:

http://examples.kevinchisholm.com/backbone/routes/basics/js/part-iii-ex2.js

How to Demo:

Below the main nav is a brown navigation menu. As you click each menu item, notice that the URL changes. For example: “#/order/chair/1” or “#/order/shirt/2”. With each click, the message in the page will reflect the parameter passed in the URL after “#/order/”, as well as the quantity (i.e. “#/order/quantity”).

But now we have a problem: If the user enters ““#/order/item” but does not specify a quantity, then the quantity will show up in the DOM as “undefined”. That’s not a good user experience, so let’s handle that exception.

Example # 3

In Example # 3, we’ve made two adjustments to our code. First, we’ve added a new route: “order/:item/”, which is handled by the “order” method. Second, we’ve added a quick check at the top of the “order” method: if (!count){count = 1}. This tells the “order” method: “hey, if the count argument is 0 or is not provided, then just make the quantity: 1).

HERE IS THE WORKING DEMO LINK FOR EXAMPLE # 3:

http://examples.kevinchisholm.com/backbone/routes/basics/html/part-iii-ex3.html

HERE IS THE LINK FOR EXAMPLE # 3’s JavaScript:

http://examples.kevinchisholm.com/backbone/routes/basics/js/part-iii-ex3.js

How to Demo:

Below the main nav is a brown navigation menu. As you click each menu item, notice that the URL changes. For example: “#/order/chair” or “#/order/shirt/”. Note that in the case of the first two links there is no quantity provided. In both cases, our “order” method sets the quantity to: 1.

Summary

In this article we learned how to pass parameters to a Backbone.js route. We learned the syntax needed to specify which part of the route request is the actual route and which part is the parameter. We discussed how to access that parameter in the function that handles the route request, how to allow for multiple parameters, and how to handle corner cases where an expected parameter is not provided.

Getting Started with Backbone.js Routes – Part II: Handling Bad Requests

Backbone

Backbone.js LogoLearn how to handle requests for a route that you have not configured

In the first part of this series: Getting Started with Backbone.js Routes – Part I: Introduction, we learned how to set up routing in a single page web application. We covered two kinds of routes: a “default” route (i.e. no route is requested), and a named route.

In this article, we will learn how to configure a Backbone router for a bad request. To be specific, a bad request would be one that you have not anticipated (i.e. you have not configured your router for that specific request). In the previous example, if you were to request a route other than “info”, there would be no error, but this is an unhandled case, and not the best user experience.

Here are two examples of unhanded exceptions from Part-I of this series:

http://examples.kevinchisholm.com/backbone/routes/basics/html/part-i.html#/bad-request

http://examples.kevinchisholm.com/backbone/routes/basics/html/part-i.html#/another-bad-request

In both cases, the page loads, but there is no message because the router was not configured to handle the routes: “#/bad-request” and “#/another-bad-request”.

Example # 1

In Example # 1, we have updated the object passed to the Backbone.Router.extend method. There is now a third route named: “*actions”. This tells Backbone that if a request is not one of the first two specified (i.e. “” and “info”), then execute the “pageNotFound” method.

The “pageNotFound” method is similar to the other route handlers, but injects a message into the DOM that is specific to this scenario: the user has requested a route that does not exist. This way, instead of “nothing” happening, you can present very specific content to the user.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 1: http://examples.kevinchisholm.com/backbone/routes/basics/html/part-ii.html

How to Demo:

When the page loads, you will see the message: “This is the default route”, and if you click the “info” link, you will see the message: This is the “Info” page. But if you click the link: “Bad request”, you will see the message: “Sorry, the page you requested was not found”. The reason for this is that there is no route configured for: “#/bad-request”. In fact, no matter what you request, unless that route request is: “” or “info”, then you will see the message: “Sorry, the page you requested was not found”

Here are a few examples:

http://examples.kevinchisholm.com/backbone/routes/basics/html/part-ii.html#/no-route-here

http://examples.kevinchisholm.com/backbone/routes/basics/html/part-ii.html#/no-route

http://examples.kevinchisholm.com/backbone/routes/basics/html/part-ii.html#/not-handled

When you click any of the links above, you will still get the message: “Sorry, the page you requested was not found”.

Summary

In this article, we learned how to configure our Backbone router to handle bad requests. We discussed the “*actions” property of the “routes” object, and how to make sure it is the last property specified in that object. We also set up a function to be executed whenever a bad route request is made.

Getting Started with Backbone.js Routes – Part I: Introduction

Backbone

Backbone.js LogoLearn the simple yet powerful syntax for setting up routing in your Backbone.js single page application

Routes are one of the most important aspects of any single page application. Routes allow you to intercept browser address changes and act upon them accordingly. As per the moniker “single page application” suggests, after the completion of the initial page load, you never want the user to endure a round-trip to the server.

Backbone.js provides simple yet powerful abstraction for routing. In this series of articles, we will explore the core syntax and features that allow you to build-out routing for your single page application.

Extending Backbone.Router

Extending classes is an important topic to quickly review. In Backbone.js, when you want to create a router, you first need to extend the Router class. To be more specific, “Router()” is a JavaScript constructor function that is a property of the “Backbone” object. Extending the Router class allows you to leverage all of the existing functionality while adding more of your own. When you extend the Router class, you are creating a new constructor that inherits from the “Backbone.Router”. Once you have extended the Router class, you’ll then need to instantiate your new constructor.

Example # 1A

Example # 1B

In example # 1A, we create a new variable named: “AppRouter”, and set it to the return value of Backbone.Router’s “extend” method. The “extend” method allows you to create a class that inherits from another and is available in a number of Backbone objects. In this case, our class does not do too much, so we have a bit more work to do.

In example # 1B, notice that an object is being passed to the extend method. This object is empty, and our AppRouter class still does not offer much value. The main points to remember as we move forward are:

You create a router by extending the Backbone.Router class, using the “extend” method
The extend method requires an object as its sole argument
The result of extending the Backbone.Router class is a new class (or constructor), which will need to be instantiated

NOTE: Our variable begins with a capital “A” (i.e. “AppRouter”). This is not required but it is recommended because in JavaScript (as well as other languages), classes usually have an initial capital letter in their name.

Example # 2

In Example # 2, we have added quite a bit of functionality to the object that is passed into the extend method. This object has three properties: “routes”, “home”, and “info”.

The “routes” property is critical. This property is an object. The properties of the object are the routes that we want to map. In this case, there are two:

  • “” – When no route is requested, map to “defaultRoute”
  • “into” – When an “info” route is requested, map to “info”

But, what are “home” and “info”? Well, they are the other two two properties of the object passed to the extend method, and they are method (i.e. they are properties whose value is a function). So, when no route is requested, Backbone will execute the “defaultRoute” method, and when the “info” route is requested, the “info” method will be executed.

This example is very basic; you are not likely to create a single page application with only two routes. What is important to remember is that as you build out your application, this is a pattern you will follow:

  • You extend the Backbone.Router class by passing an object to the extend method
  • In the object you pass to the extend method, you provide a “routes” property
  • The “routes” property is an object that has a set of properties that map to methods
  • The methods you map to are functions that handle the route request

There are still a couple of steps left in order to get our new Router to a working state.

Example # 3

In Example # 3, we take two further steps that are needed in order to get our Backbone.js router to a working state:

  1. We instantiate our AppRouter class
  2. We call Backbone.history.start(); from the jQuery document.ready method.

The first step is required because even though we extended the Backbone.Route class, we need to instantiate the new class (or constructor) that we created. A detailed discussion of the Backbone.history object and its “start” method is beyond the scope of this article, but suffice to say that this step is needed in order to get the routing process started. Wrapping it in a call to jQuery’s document.ready method is generally a good idea so that you can be sure that the routing does not start until the DOM is ready.

HERE IS THE LINK TO THIS ARTICLE’S WORKING EXAMPLE:

http://examples.kevinchisholm.com/backbone/routes/basics/html/part-i.html

How to Demo:

Click the “Home” and “Info” links in the page’s navigation menu. As you do this, look closely at the browser’s address bar. You’ll see that “#/” and “#/info” are appended to the address. These are routes. The code that we worked on in this article intercepts these route requests and prevents the page from making a request to the server located at: “http://examples.kevinchisholm.com/”. Accordingly, messages that are results of the functions we execute upon each route request are rendered in the DOM.

Details

When the page loads, you will see the following message: “This is the default route”.The reason for this is that when we extended Backbone.Route, we specified that if no route was requested, the “defaultRoute” method should execute. If you click the “Info” menu item, you’ll see the message: This is the “Info” page. This is because we specified that when the “info” route is requested, the “info” method should execute.

Summary

In this article, we were introduced to Backbone’s routing feature. We learned about extending classes, and specifically, the syntax needed to create a constructor function that inherits from Backbone.Router. We discussed the steps needed to configure our router so that a number of possible routes can be anticipated and acted upon accordingly.

Helpful Links for Routing in Backbone.js

http://backbonejs.org/#Router

http://backbonetutorials.com/what-is-a-router/

http://www.codebeerstartups.com/2013/01/routers-in-backbone-js-learning-backbone-js

Angular.js Basics: Routes Part III: Creating a Default Route (version 1.0.8)

Angular

Anuglar.js route

Learn how to create a default route in your Angular single-page app.

In Part II of this series: “Angular.js Basics: Routes Part II: Partials“, we learned how to leverage partials in order to decouple our HTML from the associated controllers. This not only proved to be fairly simple, but it also helps to keep our JavaScript code easier to manage and allows us to create HTML templates that can support a higher degree of complexity.

But in the previous example, when our page loaded, the element with the ngView directive was empty by default. So, the user was required to click a link in order for us to display any content provided by a partial.

In this article, we will learn about a new method of the $routeProvider object that allows us to tell Angular which partial to inject into the DOM when the base page loads.

Two things to note: 1) This article is specific to Angular 1.0.8.   2) The example code that follows leverages code from Part II of this series: “Angular.js Basics: Routes Part II: Partials“. For the sake of brevity, I won’t review much of what we learned in the previous article in great detail. If you are completely new to the idea of Angular Routes, I highly recommend you read Parts I and II of this series, and then return here.

You can download a working version of this code here: https://github.com/kevinchisholm/angular-1.0.8-default-route

The JavaScript file with the code samples you see below can be found in the file: www/js/myApp.js

Configuring your routes

Example # 1

In Example # 1, we re-visit the function expression: configFunction. You may recognize the two calls to $routeProvider.when(). These let angular know how we want it to handle requests to the routes “/hello” and “/goodbye”. In both cases, I’ve omitted the properties of the object that makes up the second argument to that method call, just to keep the example code to a minimum (these details were covered in Part I and Part II of this series).

The otherwise method

What follows those two calls is the .otherwise() method of the $routeProvider object. This method tells Angular what to do if the current request does not match any of the ones specified by the one or more calls we have made to the $routeProvider.when() method.

This is quite a useful feature. It allows us to continue to leverage an Angular partial that will be injected into the DOM by default. A typical scenario for this would be some kind of “home” page. Since the examples provided in this series are focused around the routes “/hello” and “/goodbye”, I decided that when neither route has been requested, I’d like to show the message “Hello!”. I’ve leveraged the same partial file: “message.html”, but the inline anonymous function that is assigned to the “controller” property sets the value of $scope.message” to “Welcome!”. The end result is that when you load the base page (i.e. part-3.html), the default message is “Welcome!”.

Example # 2

In Example # 2, we have added two hyperlinks to our navigation component: “Home” and “Bad Route”. The “Home” link simply requests an unspecified route: “#/”, which displays the default content “Welcome!”. We have specified this in the controller that is a property of the object passed to the $routeProvider.otherwise() method.

 

There is also a link named “Bad Route”, which requests the route: “/badroute”. Since we have not told Angular what to do when this route is requested, the details provided in our call to the $routeProvider.otherwise() method tells Angular to also display the default content: “Hello!”. But a subtle problem we have is the hash. In this case, the URL in the address bar will show: “#/badroute”, even though Angular does as we ask, and displays the default content. The problem here is that we are giving the user an opportunity to deep-link this URL, even though it is an un handled route. We need to fix this.

the redirect-to property

Example # 3

In Example # 3, we have added a new property to the object that is passed to the $routeProvider.otherwise() method: “redirectTo”. This tells Angular that when a route that we have not specified is requested, then in addition to using the specified partial and controller, it should re-direct the requested route to the “root” of our application. We could also specify another valid route, for example “/login”, etc. In this case, we simply want the address bar to show the root of the app. This way, when the user requests a route that is un handled, that request fails gracefully.

Example # 4

In Example # 4, we have the full code for our working example.

View and test the full working example code

HERE IS THE LINK FOR THE FULL WORKIG EXAMPLE: http://examples.kevinchisholm.com/javascript/angular/routes/part-3.html

How to Demo: In the blue box, you’ll notice two hyperlinks: “Hello” and “Goodbye”. Click either one of those links. When you click either link, you’ll notice that the appropriate HTML is injected into the DOM on the right side of the page. Note as well that in your browser’s address bar, “#hello” and “#goodbye” are appended to the URL. This is Angular’s way of providing support for deep-linking. The web page you are on never refreshes, but the hash portion of the URL changes.

Differences in the code

The main difference between this example and the same one from Part # 2 of our series is our use of a default route. When the page initially loads, the message “Welcome!” is displayed. The reason why this happens is: we have specified that message in our call to the $routeProvider.otherwise() method. Also, if you click the link: “Bad Route”, the default route is displayed as well. From Angular’s perspective, it is the exact same scenario: the user has requested a route that has not been specified, so our default route is used.

Summary

In this article, we learned how to create a default Angular.js route. While covering this topic, we focused on the the $routeProvider.otherwise method, which tells Angular how to handle a request for a route that has not been specified by a call to the $routeProvider.when() method. We also discussed the importance of the “redirectTo” property, which tells Angular to redirect to a route that has been properly configured, which makes for a better user experience.

here are some Helpful Links for the $routeProvider.otherwise method

http://docs.angularjs.org/api/ngRoute.$routeProvider

https://www.bitcast.io/b/getting-started-with-angularjs?v=angularjs-routeprovider-api

http://vxtindia.com/blog/8-tips-for-angular-js-beginners/

Angular.js Basics: Routes Part II: Partials

Angular

Angular.js LogoLearn how to use partial templates in your Angular single-page app.

In the first article of this series: “Angular.js Basics: Routes Part I,” we learned how Angular can intercept a hyperlink click, and inject HTML into the DOM. Accomplishing this is surprisingly straightforward because Angular provides a great deal of abstraction with regard to preventing a full-page refresh, DOM manipulation, and deep-linking via the hash.

In that previous post, the HTML that we injected into the DOM was a string that was assigned to the “template” property of the object passed to the $routeProvider.when() method. While this makes it easy to accomplish our task, it is not optimal because we are mixing with JavaScript. Also, a real-world scenario might require markup significantly more robust than the simple one-line string we use (i.e. <h1>{{message}}</h1>). What we need is the ability to leverage HTML that is separate from our JavaScript code, and could be hundreds, even thousands of lines of markup. Most importantly, our JS controller should have no concern for the markup we use; its only job is to be told where it is, and then inject it into the DOM.

An Angular partial is simply an HTML file. The main difference between this and a full-fledged web page is that the partial contains only the HTML we need. There is no need for a !DOCTYPE declaration, HTML, HEAD or BODY elements. The HTML in this file will be injected into the current web page, so only the markup that makes-up the actual component is needed.

Note: The example code that follows leverages code from Part I of this series: “Angular.js Basics: Routes Part I”. For the sake of brevity, I won’t review much of what we learned in the previous article in great detail. If you are completely new to the idea of Angular Routes, I highly recommend you read that article first, and then return here.

Example # 1

In Example # 1, we have the entire contents of the file message.html. This file sits in the same folder as our web page. As you can see, it contains only two lines of HTML: an H1 tag and a paragraph tag. There is also a set of double-curly-braces in the paragraph tag. As per our discussion in the last article, this is a placeholder for the “message” property of the $scope object to which this element is bound.

Example # 2

In Example # 2, we have our call to the $routeProvider.when() method. As per the previous article’s discussion, this method takes two arguments: the path that we want Angular to respond to, and an object that tells Angular how to handle this request.

The code in Example # 2 is virtually identical from that of the previous article with one exception: Instead of using a “template” property, we are now using a property named “templateUrl”. What this tells Angular is:

When the user requests “/hello”, do not actually direct the browser to that path.
Load the file “message.html” via ajax, and inject it into the DOM
In “message.html”, replace {{message}} with the value of $scope.message

While all of this occurs in virtually milliseconds, it is important to note that these steps are, in fact, executed by Angular.

Example # 3

In Example # 3, we have made the same change to the $routeProvider.when() method call for the path “/goodbye”.

Example # 4

HERE IS THE LINK FOR FULL WORKING EXAMPLE: http://examples.kevinchisholm.com/javascript/angular/routes/part-2.html

How to Demo: In the blue box, you’ll notice two hyperlinks: “Hello” and “Goodbye”. Click either one of those links. When you click either link, you’ll notice that the appropriate HTML is injected into the DOM on the right side of the page. Note as well that in your browser’s address bar, “#hello” and “#goodbye” are appended to the URL. This is Angular’s way of providing support for deep-linking. The web page you are on never refreshes, but the hash portion of the URL changes.

The main difference between this example and the same one from Part 1 of our series is our use of partials. Instead of hard-coding an HTML string in our JavaScript controller by assigning it to the ‘template” property, we specify a “templateUrl” property and assign a value that points to an HTML file containing only the markup we need.

Summary

In this article, we learned how to leverage Angular partials. Instead of hard-coding some HTML in our JavaScript file, we tell Angular where to find an HTML file that contains the markup we need. The main advantage here is the ability to decouple our JavaScript from the presentation code. And the HTML files that comprise our partials can be as large or complex as we like.

Helpful Links for Angular Partials

http://docs.angularjs.org/tutorial/step_07

http://onehungrymind.com/building-a-website-with-angularjs-routes-and-partials/

Angular.js Basics: Routes Part I

Angular

Learn how to spin-up an AJAX-driven single-page app by leveraging Angular.s Routes

Single-page applications have become a common project for many front-end web developers. The key components to any such endeavor is the ability to intercept hyperlinks, the updating of the DOM without actually refreshing the page, and support for deep-linking.

Anyone who has attempted even the most basic single-page application knows that managing this kind of interaction on the client-side can be tedious. Angular.js provides a significant level of abstraction when it comes to these kinds of tasks. In a few dozen lines of code, you can quite easily spin-up an AJAX-driven single-page app by leveraging Routes & Views.

Example # 1

In Example # 1, we have added the ng-app directive to the BODY tag. The value is “mainRouter”, which means there must be an Angular module by that name available. We will create this module shortly.

Example # 2

In Example # 2, we have two hyperlinks. Note that the values provided for each element’s HREF attribute are preceded by a hash. This allows Angular to intercept the hyperlink, process the request and prevent the page from following the URL (which would result in an error).

Example # 3

In Example # 3, we have an empty element with an ng-view directive. This is the element into which Angular will inject the HTML templates that we specify.

Example # 4

In Example # 4, we have created an Angular module. This is done by assigning a variable to the return value of a call to the angular.module() method. This method takes two arguments: the name of our module as a string (required), and an array of dependencies (optional). Although the second parameter is optional, because these dependencies are provided via an array, if you do not specify any dependencies, you must still include an empty array.

Example # 5

In Example # 5, we configure our router module by calling it the config() method. This method takes an array as an argument. The first element of the array is the $routeProvider object (which we will use shortly), and the name of a function that will execute our configuration code. It is perfectly acceptable (and quite common) to provide an inline anonymous function for the second parameter. I have specified a function expression instead, simply to keep the example code straightforward and easy to understand.

Example # 6

In Example # 6, we have a function named configFunction(). This function expression is passed to the config() method of our myRouter module. It takes the $routeProvider object as its sole argument. The real action takes place as we make a call to the $routeProvide’s when() method. This method expects two arguments: the URL to watch for, and an object. The properties of that object allow us to tell Angular a number of things about what should happen when the specified URL is requested by the user.

The specified URL is not a fully-qualified web address that starts with “http://”. Instead, we specify a path that is relative to the current page. The general approach is that this path should resemble a RESTful API address.

Examples:

  • http://www.some-domain.com/users (would return a list of users)
  • http://www.some-domain.com/users/1 (would return the user with the ID of “1”)
  • http://www.some-domain.com/users/add (would allow you to add a user)
  • http://www.some-domain.com/users/remove (would allow you to remove a user)
  • Etc…

A discussion of RESTful web services is out of the scope of this article. If you are not familiar with that topic, there are a few links at the bottom of this page that you might find helpful.

In the case of Example # 6, we have told Angular that when the user clicks a link that points to: “/hello”, two things should happen:

  1. The element with the ngView directive should have the HTML string assigned to the “template” property injected into it (i.e.<h1>{{message}}</h1>)
  2. The inline anonymous function that is assigned to the “controller” property should be executed.

A few things to note about these two actions that Angular takes:

In the HTML string that is injected into the element with the ngView directive, there is a set of double-curly-braces. This functions as a client-side template. When the specified HTML is injected into the DOM, the value of the “message” variable is inserted inside of that set of double-curly-braces. That value is provided by the function assigned to the “controller” property of this object passed to the $routeProvide’s when() method. That function takes the $scope object as an argument, and inside of the function, the string: “Hello!” is assigned to the “message” property of the $scope object.

Note: Once again, please note that this function expression could have been defined inline as an anonymous function when we made the call to myRouter.config() in Example # 5. The reason that I chose to break it out like that is because it made it easier to demonstrate the critical pieces of code, while keeping them fairly simple.

Example # 7

In Example # 7, we have added another route: “/goodbye”. So when the user requests that URL, the exact same actions taken in Example # 6 will be performed by Angular, with the only difference being the value of $scope.message: “GoodBye!”.

Example # 8

In Example # 8, we have the full code for our working example.

HERE IS THE LINK FOR OUR FULL WORKING EXAMPLE # 8: http://examples.kevinchisholm.com/javascript/angular/routes/part-1.html

How to Demo: In the blue box, you’ll notice two hyperlinks: “Hello” and “Goodbye”. Click either one of those links. When you click either link, you’ll notice that the appropriate HTML is injected into the DOM on the right side of the page. Note, as well, that in your browser’s address bar, “#hello” and “#goodbye” are appended to the URL. This is Angular’s way of providing support for deep-linking. The web page you are on never refreshes, but the hash portion of the URL changes. If you were to copy and paste http://examples.kevinchisholm.com/javascript/angular/routes/part-1.html#/hello or http://examples.kevinchisholm.com/javascript/angular/routes/part-1.html#/goodbye into another browser, your single-page app would “link” to that desired behavior. What is really happening is that Angular is intercepting any request that comes after the hash, and taking the actions that we specified in Examples # 6 and # 7. If you were to remove the hash from either URL, you would receive an error because the URL http://examples.kevinchisholm.com/javascript/angular/routes/part-1.html/goodbye is not valid.

Summary

In this article, we discussed Angular.js routes, a powerful feature that allows you to create fully-functioning single-page web apps with minimal effort. We talked about how to create an Angular module, configure that module, and call the $routeProvider.when() method in order to tell Angular how to intercept specific URL requests without refreshing the page, and inject the appropriate HTML into the DOM. We also discussed how this feature is based on RESTful URL syntax.

Helpful Links for Angular.js Routes and RESTful Web services

Angular.js Routes

http://docs.angularjs.org/api/ngRoute.$route

http://docs.angularjs.org/api/ngRoute

http://viralpatel.net/blogs/angularjs-routing-and-views-tutorial-with-example/

RESTful Web services

 

http://searchsoa.techtarget.com/definition/REST

http://www.ibm.com/developerworks/webservices/library/ws-restful/