angular-js router

Getting started with Angular-js Router

Angular-js is an awesome MVC framework for javascript.Routing and Deep-linking is an important part of any web application because just a state can be shared directly via the url.
Angular-js Router is one of the most important part an ng-app.

Important Links :-

Github link

Docs for ngRoute
Docs for $routeProvider
Docs for ngView
Download angular-route.min.js

1.Simple Start

Since Angular version 1.2 , you need to angular-route is in a different module and needs to be included seperately .
$routeProvider is angular module where we define the templateUrl and the controller.We need to define the routes inside App.config and give the template Url.The template can be defined inside script tags
<script type= text/ng-template>Your html Template</script>
or can be externally included.

ng-view is the directive that directly complements $route.

ngView is a directive that complements the $route service by including the rendered template of the current route into the main layout (index.html) file. Every time the current route changes, the included view changes with it according to the configuration of the $route service.

Here’s the most simple version of an angular app running ngRoute

App.config(function  ($routeProvider,$locationProvider) {
    $routeProvider.when("/hello",{ templateUrl : "hello.html"});
    $locationProvider.html5Mode(true);//We are using the html5 mode to make it work in plunkr
});

2.Multiple routes and otherwise

Here’s Another example that makes use of .otherwise() of $routeProvider.
From docs :
.otherwise() sets route definition that will be used on route change when no other route definition is matched.
ngRouter lets you define different paths and their corresponding templates and controllers at the end you can define a otherwise function to redirect or use a template when there is url hash which has not been defined.Its important for error handling.
The Route path is matched against $location.path and if $location.path contains redundant trailing slash or is missing one,the route will still match and the $location.path will be updated to add or drop the trailing slash to exactly match the route definition.

$routeProvider
	.when("/link1",{
		templateUrl : "js/hello.html" , controller : "ChildCtrl1"
	})
	.when("/link2",{
		templateUrl : "js/hello2.html" , controller : "ChildCtrl2"
	})
	.otherwise({
		templateUrl : "js/hello3.html"
	});

Here’s the plnkr for it

3.Using $routeParams

The path defined in $routeProvider can contain named groups starting with a colon and ending with a star: e.g.:name*. All characters are eagerly stored in $routeParams under the given name when the route matches.

For example /list/:id will match /list/1 and give $routeParams.id = 1.

The path can contain optional named group parameters with a question mark.FOr e.g.link1?search=hello will give
$routeParams.search = "hello"

Here’s is the plnkr for that

4.Loading a template according a condition

There are 2 simple ways to load or redirect to a particular route according to some variable or condition.

Here’s is the first way using resolve method :

According to docs ,

resolve - {Object.=} - An optional map of dependencies which should be injected into the controller.If any of these dependencies are promises,the router will wait for them all to be resolved or one to be rejected
 before the controller is instantiated.If all the promises are resolved successfully, the values of the resolved promises are injected and $routeChangeSuccess event is fired.If any of the promises are rejected the $routeChangeError event is fired.

To make use of it , lets say we have a boolean variable isCurrentTaskDone defined on $rootScope, which decides whether we should go to the next task.

If the user clicks on the next task , we can check the $rootScope for the boolean value , if true then the factory will return true , and if false the app gets redirected using $location service to /link1.

Here’s the code

App.run(function  ($rootScope) {
	$rootScope.isCurrentTaskDone = false;
});

App.config(function  ($routeProvider,$locationProvider) {
	$routeProvider
	.when("/link1",{
		templateUrl : "js/hello.html" ,
		controller : "ChildCtrl1",
		resolve : {
			factory : function  ($rootScope,$location) {
				if ($rootScope.isCurrentTaskDone) {
					return true;
				}else{
					$location.path('/link2');
					return false;
				}
			}
		}
	})
	.when("/link2",{
		templateUrl : "js/hello2.html",
		controller : "ChildCtrl2"
	})
	.otherwise({
		templateUrl : "js/hello3.html"
	});
	$locationProvider.html5Mode(true);//required to work in plnkr
});

Here’s is the plnkr demo

4 thoughts on “Getting started with Angular-js Router”

    1. It doesn’t work because Java script gets refreshed and all the variables, including $rootScope are reinitialized. There is no way.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>