Wednesday, 19 February 2014

Routing in AngularJs

On this post we will see the basic of how to create Single Page Application with AngularJs.

First we need to add reference to AngularJs routing library.
<script src="Scripts/angular.min.js"></script>
<script src="Scripts/angular-route.min.js"></script>

Then we add dependency to ngRoute module in our application module.
var myApp = angular.module('myApp', ['ngRoute']);

Next, use $routeProvider service that will be available after we include the new module to configure the routes that we have. The basic syntax is as follow:
$routeProvider.when('desired_path'), {
    templateUrl: 'location_of_the_partial_view_file',
    controller: 'controller_name_for_this_partial_view'
}
The path can contain route parameter(s) which is specified with colon (:) and could end with a star (*). Also we could have an optional parameter with a question mark (?). For more information, please see $routeProvider documentation.

Below is an example of a routes configuration:
myApp.config(['$routeProvider', function ($routeProvider) {
    $routeProvider
    .when('/pageOne', {
        templateUrl: 'partials/page-one.html',
        controller: 'PageOneCtrl'
    })
    .when('/pageTwo', {
        templateUrl: 'partials/page-two.html',
        controller: 'PageTwoCtrl'
    })
    .otherwise({
        redirectTo: '/'
    });
} ]);

Finally we use ng-view directive to apply the configuration in our main view. For example:
<div data-ng-view></div>

Below is an example of the complete main view:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" data-ng-app="myApp">
<head>
    <title></title>
    <script src="http://code.angularjs.org/1.2.9/angular.min.js" type="text/javascript"></script>
    <script src="http://code.angularjs.org/1.2.9/angular-route.min.js" type="text/javascript"></script>
    <script src="Scripts/app.js" type="text/javascript"></script>
    <script src="Scripts/Home/page-one-controller.js" type="text/javascript"></script>
    <script src="Scripts/Home/page-two-controller.js" type="text/javascript"></script>
</head>
<body>
    <a href="#">Home</a> | <a href="#pageOne">Page One</a> | <a href="#pageTwo">Page Two</a>
    <div data-ng-view></div>
</body>
</html>

If we want to use HTML5 url mode that is supported by recent browsers, on myApp.config(...) method add a dependency to $locationProvider service then add this line inside the method:
$locationProvider.html5Mode(true)

No comments: