Sunday, 6 September 2015

Angular Routing Tutorial: Learning ng-Route and ui-Router




Well, In our last tutorial, we learnt about Controllers but before we are ready to move ahead with a mini application, we must learn about Angular routing. Every framework generally provides a routing mechanism to browse through different pages of the application. The basic routing mechanism that angular offers is ng-Route, however, there also is an ui-router component that is widely used with angular applications. We shall learn to use both in this tutorial.

ng-Route:

The first thing you need to know about ng-Route is that its not the integral part of angular.js. So you need to go to angularjs.org  or this link and download the ng-Route plugin and use it in your application.

Once you have included it in your index.html file, you need to inject it as a dependency in your app/module declaration as below. You can do this in a different js file of your choice, but I prefer to use the app.js file for keeping routing level code.

angular .module('myModule', ['ngRoute']) ;

In case, you have been wondering those [ ] in declaration of module, now you know that these [ ] are to include the external dependencies. So now we are good to go for using it.

How to use ng-Route:

In your index.html file or the basic html page you need to declare a ng-view attribute where all your other pages will be loaded. This can be done anywhere where you like your page to load. For example:

<!DOCTYPE HTML>
<html ng-app="myModule">
<head>
    <title>AngularJS Tutorials</title>
    <script src="scripts/angular.min.js"></script>
    <script src="scripts/angular-route.min.js"></script>
    <script src="scripts/jquery.min-1.11.3.js"></script>
    <script src="scripts/jquery-ui.js"></script>
    <script src="scripts/Ctrl1.js"></script>
    <script src="scripts/Ctrl2.js"></script>
</head>
    
    <body>
    <header>
        <h2>AngularJS Tutorials</h2>
    <h3>Simple AngularJS application</h3>    
    </header>
        <div ng-view>
        <!-- This is a comment. The view will load in this region -->
        </div>
    </body>
</html>

Now is the time to show the actual code for routing our pages. Consider the code snippet below:


angular.module('myModule', ['ngRoute'
  ])
  .config(function ($routeProvider) {

    $routeProvider
      .when('/page1', {
        templateUrl: 'views/page1.html',
        controller: 'Ctrl1'
      })
      .when('/page2', {
        templateUrl: 'views/page2.html',
        controller: 'Ctrl2',
      })
      .otherwise({
        redirectTo: '/'
      });
  });

In the above example, myModule is as usual our application name. .config is an method to configure the routing parameters. $routeProvider is an angular service whose .when() method is called for routing. This method takes two mandatory arguments:
  1. Url: The URL that the browser should display for this specific page. This URL is appended to the base URL of the application.
  2. A JavaScript object containing:
  • templateUrl: The path of the HTML file to load.
  • controller: The controller that should be called for any action on the loaded HTML.
While the ng-Route is well enough for a basic application, it has the limitation that it can't again load a page somewhere within the loaded page i.e nested views.

Angular-ui-router:

To overcome this limitation, we will learn to use ui.router. Although its not a part of AngularJS, its a freeware and can be downloaded from this link. Similarly as ng-Route you need to include the downloaded js file in your index.html

States:

As I mentioned before, each view or html page (also known as partials) is assigned with a controller, which handles the event on that html page. This view is characterized by a unique segment of URL, so that when this page loads, your browser shows a different URL.
Hence when we say a state, we refer to a combination of:

  • An HTML view
  • A controller and 
  • A URL
Its not mandatory but good to have a unique combination of these 3 components for every state.

How to use ui-router:

In your index.html file or the basic html page you need to declare a ui-view attribute where all your other pages will be loaded. This can be done anywhere where you like your page to load. A child view will be loaded in ui-view tag provided within its parent page. For example:

<!DOCTYPE HTML>
<html ng-app="myModule">
<head>
    <title>AngularJS Tutorials</title>
    <script src="scripts/angular.min.js"></script>
    <script src="scripts/angular-ui-router.min.js"></script>
    <script src="scripts/jquery.min-1.11.3.js"></script>
    <script src="scripts/jquery-ui.js"></script>
    <script src="scripts/Ctrl1.js"></script>
    <script src="scripts/Ctrl2.js"></script>
</head>
    
    <body>
    <header>
        <h2>AngularJS Tutorials</h2>
    <h3>Simple AngularJS application</h3>    
    </header>
        <div ui-view>
        <!-- This is a comment. The view will load in this region -->
        </div>
    </body>
</html>

The usage of ui-router is not much different from the native ng-Router. Consider the code snippet below:

angular
.module('myModule', ['ui.router' ])
.config(function ($stateProvider) {
    $stateProvider
.state('loginState',{
url:'/login',
templateUrl:'views/LoginPage.html',
controller:'LoginCtrl'
})
        .state('home', {
url:'/home ',
                 templateUrl: 'views/HomeView.html',
controller:'HomeCtrl'
})
.state('home.page1',{
url:'/page1', 
templateUrl: 'views/FirstPage.html',
controller:'FirstPageCtrl'
})
});

You can define as many states as you need.In this example, the third state i.e. home.page1 is a child state of home. It means this state will be loaded inside the home page. So every time this state is called the HomeView.html is loaded with FirstPage.html somewhere within it.

The above code is almost similar to the ng-route code, except for the fact that here we injected ui.router as the dependency. Also the routes are now handled by a $stateProvider service by using the .state() method. This method takes two mandatory inputs:

  1. A name of the state, which can be any name of your choice.
  2. A JavaScript object containing:
  • URL of the page to be loaded
  • Path of the page to be loaded
  • Controller that is to be called for actions on that page. 
You have additional advantages of using ui.router. In ui.router, you just declare a state in your config and can call that state name from any link in your application using ui-sref keyword as below:

<a ui-sref='login' >Login</a>

Clicking this link will produce the same effect as of loading a state and will load the LoginPage.html page. Also from anywhere in your JavaScript code you can control the flow of your application by loading a state depending on your requirement. For example:

if(something){
$state.go('home.page1');
}
else{
$state.go('home.login');
}

So basically, this is all basic about the angular routers. Going ahead will be following a basic app to explain more details and features of AngularJS and we will be using angular-ui-router for it. Stay tuned.

No comments:

Post a Comment

Your valuable comments on this post are welcomed. Think something is missing, something is inappropriate or want to share something???
Please feel free to comment..