Thursday, 21 April 2016

Routing in angular js

1, download angular-route.min.js from https://code.angularjs.org/1.5.5/
2, include angular-route.min.js file to your application using script tag
   <script src="angular-route.js">

3, Then load the module in your application by adding it as a dependent module:
   angular.module('myApp', ['ngRoute']);

With that you can use all the methods, providers, services in ng-route module

ngRoute:
The ngRoute module provides routing and deeplinking services and directives for angular apps.

ngView:
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.

Example:

1, Create 2 html files named as route1.html and route2.html respectively in views folder.
2, inject ngRoute module to myApp module.
   angular.module('myApp', ['ngRoute']);

3, In config use $routeProvider to configure routes
   angular.module('myApp', ['ngRoute']).config(['$routeProvider', function($routeProvider){
    $routeProvider.when('/route1', {
templateUrl: 'views/route1.html',
}).when('/route2', {
templateUrl: 'views/route2.html',
});
   }])
4, In index.html create two links use anchor tag.
<a href="#/route1">route1</a> |
  <a href="#/route2">route2</a>
5, Add ng-view in index.html
<div ng-view></div>

that's it...now refresh your index.html and then check it.. :-)

No comments:

Post a Comment