AngularJS Routing and Views Tutorial with Example

angular-js-logo

Welcome to the next tutorial of the ongoing series of tutorials on AngularJS. In previous tutorial we saw AngularJS Controllers and also created a Hello World example using Angular. In this article we will go through the next useful feature of AngularJS called Routing. Also we will see how we can divide a single page application in multiple views. As we add more and more logic to an app, it grows and soon become difficult to manage. Dividing it in Views and using Routing to load different part of app helps in logically dividing the app and making it more manageable. Routing helps you in dividing your application in logical views and bind different views to Controllers.

angularjs-routing-view-controller

In above diagram we create two Route url /ShowOrders and /AddNewOrder. Each points to a specific view and is managed by a controller. Don’t panic if it does not make any sense. Soon we will see some code and it all will be clear.

1. Introduction to $routeProvider

The magic of Routing is taken care by a service provider that Angular provides out of the box called $routeProvider. An Angular service is a singleton object created by a service factory. These service factories are functions which, in turn, are created by a service provider. The service providers are constructor functions. When instantiated they must contain a property called $get, which holds the service factory function. When we use AngularJS’s dependency injection and inject a service object in our Controller, Angular uses $injector to find corresponding service injector. Once it get a hold on service injector, it uses $get method of it to get an instance of service object. Sometime the service provider needs certain info in order to instantiate service object. Application routes in Angular are declared via the $routeProvider, which is the provider of the $route service. This service makes it easy to wire together controllers, view templates, and the current URL location in the browser. Using this feature we can implement deep linking, which lets us utilize the browser’s history (back and forward navigation) and bookmarks. Syntax to add Routing Below is the syntax to add routing and views information to an angular application. We defined an angular app “sampleApp” using angular.module method. Once we have our app, we can use config() method to configure $routeProvider. $routeProvider provides method .when() and .otherwise() which we can use to define the routing for our app.

var sampleApp = angular.module('phonecatApp', []); sampleApp .config(['$routeProvider', function($routeProvider) { $routeProvider. when('/addOrder', { templateUrl: 'templates/add-order.html', controller: 'AddOrderController' }). when('/showOrders', { templateUrl: 'templates/show-orders.html', controller: 'ShowOrdersController' }). otherwise({ redirectTo: '/addOrder' }); }]);
Code language: JavaScript (javascript)

In above code we defined two urls /addOrder and /showOrders and mapped them with views templates/add-order.html and templates/show-orders.html respectively. When we open http://app/#addOrder url in browser, Angular automatically matches it with the route we configures and load add-order.html template. It then invokes AddOrderController where we can add logic for our view.

1.1. Hello World AngularJS + Routing

Let us go through an example in AngularJS and use Routing to load different templates at runtime. Below sample1.html file is the main html file. It includes AngularJS library and define structure for our app. We have two links: Add New Order and Show Order. Each link loads template in below section.

sample1.html

<!DOCTYPE html> <html lang="en"> <head> <title>AngularJS Routing example</title> </head> <body ng-app="sampleApp"> <div class="container"> <div class="row"> <div class="col-md-3"> <ul class="nav"> <li><a href="#AddNewOrder"> Add New Order </a></li> <li><a href="#ShowOrders"> Show Order </a></li> </ul> </div> <div class="col-md-9"> <div ng-view></div> </div> </div> </div> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script> <script src="app.js"></script> </body> </html>
Code language: HTML, XML (xml)

ng-view

One thing worth noting is the ng-view directive. In our angular app, we need to define ng-app directive once. This becomes the placeholder for views. Each view referred by the route is loaded in this section of document. You can define ng-view in main html file in one of the below way.

<div ng-view></div> .. <ng-view></ng-view> .. <div class="ng-view"></div>
Code language: HTML, XML (xml)

1.2. Add Routing in AngularJS

In above sample1.html file we included a javascript file app.js which holds the application logic. Below is the content of app.js.

app.js

//Define an angular module for our app var sampleApp = angular.module('sampleApp', []); //Define Routing for app //Uri /AddNewOrder -> template add_order.html and Controller AddOrderController //Uri /ShowOrders -> template show_orders.html and Controller AddOrderController sampleApp.config(['$routeProvider', function($routeProvider) { $routeProvider. when('/AddNewOrder', { templateUrl: 'templates/add_order.html', controller: 'AddOrderController' }). when('/ShowOrders', { templateUrl: 'templates/show_orders.html', controller: 'ShowOrdersController' }). otherwise({ redirectTo: '/AddNewOrder' }); }]); sampleApp.controller('AddOrderController', function($scope) { $scope.message = 'This is Add new order screen'; }); sampleApp.controller('ShowOrdersController', function($scope) { $scope.message = 'This is Show orders screen'; });
Code language: JavaScript (javascript)

We first use .config() method to define $routeProvider configuration. Also in the same file we define two controllers AddOrderController and ShowOrdersController. In a real world application these controllers will hold a lot of logic but for example sake we just define a message property on $scope which later we use to display on view. Notice how we used otherwise() method to define a default route. In case routeProvider does not matche with any url, it redirects to default route.

... otherwise ({ redirectTo: '/AddNewOrder' });
Code language: JavaScript (javascript)

1.3. Add HTML template files

Our app.js is ready. We still needs to define two html templates. These are partial templates of our app.

templates/add_order.html

<h2>Add New Order</h2> {{ message }}
Code language: HTML, XML (xml)

add_order.html template should have an html form for adding new orders. For sake of simplicity we just show a message.

templates/show_orders.html

<h2>Show Orders</h2> {{ message }}
Code language: HTML, XML (xml)

1.4. Online Demo

Click links in below example to load different template based on Uri.

Demo link: Plnkr.co

2. How to pass Parameters in Route Urls

We saw how to define route in above example. Now let us see how can we define parameters in route urls. Consider below scenario. We want to display details of different orders. Based on a parameter order_id we will define order details in view.

angularjs-route-parameters

In angular while define route we can define parameters using orderId in url. For example:

when('/ShowOrder/:orderId', { templateUrl: 'templates/show_order.html', controller: 'ShowOrderController' });
Code language: JavaScript (javascript)

And we can read the parameter in ShowOrderController by using $routeParams.orderId.

... $scope.order_id = $routeParams.orderId; ...
Code language: JavaScript (javascript)

Let us checkout a sample application. Below sample2.html is main html page which describe the structure. It contains order information data in tabular format. Each order has a “show details” link. This link uses parametrize route url to load order detail screen.

sample2.html

<!DOCTYPE html> <html lang="en"> <head> <title>AngularJS Routing example</title> </head> <body ng-app="sampleApp"> <div class="container"> <div class="row"> <div class="col-md-9"> <table class="table table-striped"> <thead> <tr> <th>#</th><th>Order No.</th><th>Details</th><th></th> </tr> </thead> <tbody> <tr> <td>1</td><td>1234</td><td>15" Samsung Laptop</td> <td><a href="#ShowOrder/1234">show details</a></td> </tr> <tr> <td>2</td><td>5412</td><td>2TB Seagate Hard drive</td> <td><a href="#ShowOrder/5412">show details</a></td> </tr> <tr> <td>3</td><td>9874</td><td>D-link router</td> <td><a href="#ShowOrder/9874">show details</a></td> </tr> </tbody> </table> <div ng-view></div> </div> </div> </div> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script> <script src="app.js"></script> </body> </html>
Code language: HTML, XML (xml)

app.js

var sampleApp = angular.module('sampleApp', []); sampleApp.config(['$routeProvider', function($routeProvider) { $routeProvider. when('/ShowOrder/:orderId', { templateUrl: 'templates/show_order.html', controller: 'ShowOrderController' }); }]); sampleApp.controller('ShowOrderController', function($scope, $routeParams) { $scope.order_id = $routeParams.orderId; });
Code language: JavaScript (javascript)

Note: Don’t forget to inject $routeParam parameter in controller. Otherwise you wont be able to use it.

templates/show_order.html

<h2>Order #{{order_id}}</h2> Here are the details for order <b>#{{order_id}}</b>.
Code language: HTML, XML (xml)

2.1 Online Demo

Click the show details links on different orders.

Demo link: Plnkr.co

3. How to Load local views (Views within script tag)

It is not always that you want to load view templates from different files. Sometimes the view templates are small enough that you might want them ship with main html instead of keeping them in separate html files.

3.1 ng-template directive

You can use ng-template to define small templates in your html file. For example:

<script type="text/ng-template" id="add_order.html"> <h2> Add Order </h2> {{message}} </script>
Code language: HTML, XML (xml)

Here we defined a template “add_order.html” inside <script> tag. Angular will automatically load this template in ng-view whenever add_order.html is referred in route. Let us quickly go through a sample app where we use local view definitions. sample3.html defines structure of app. It is similar to the first example that we saw (sample1.html) with a bit of change. We defined two views add_order.html and show_orders.html within sample1.html as <script> tag.

sample3.html

<!DOCTYPE html> <html lang="en"> <head> <title>AngularJS Routing example</title> <link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"> </head> <body ng-app="sampleApp"> <div class="container"> <div class="row"> <div class="col-md-3"> <ul class="nav"> <li><a href="#AddNewOrder"> Add New Order </a></li> <li><a href="#ShowOrders"> Show Order </a></li> </ul> </div> <div class="col-md-9"> <div ng-view></div> </div> </div> </div> <script type="text/ng-template" id="add_order.html"> <h2> Add Order </h2> {{message}} </script> <script type="text/ng-template" id="show_orders.html"> <h2> Show Orders </h2> {{message}} </script> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script> <script src="app.js"></script> </body> </html>
Code language: HTML, XML (xml)

The app.js is similar to first sample. There is no change in app.js. Refer to first demo example if you wanna check app.js.

3.2 Online Demo

Click the show details links on different orders.

Demo link: Plnkr.co

4. Add Custom Data to RouteProvider

The $routeProvider provides methods when() and otherwise() which we used to define url routes. Sometime we might want to pass custom data based on certain route. For example you might use same Controller in different routes and use some custom data. For example:

when('/AddNewOrder', { templateUrl: 'templates/add_order.html', controller: 'CommonController', foodata: 'addorder' }). when('/ShowOrders', { templateUrl: 'templates/show_orders.html', controller: 'CommonController', foodata: 'showorders' }); sampleApp.controller('CommonController', function($scope, $route) { //access the foodata property using $route.current var foo = $route.current.foodata; alert(foo); });
Code language: JavaScript (javascript)

In above code we defined a new property “foodata” while defining route. This property is then accessed in controller using $route.current.foodata.

References

  1. AngularJS documentation on $routeProvider
  2. AngularJS documentation on View & Routing
  3. Mapping AngularJS Routes Onto URL Parameters And Client-Side Events

That’s All Folks

Hope this tutorial helped you in understanding Routing and views concept of AngularJS. In case you missed previous tutorials on AngularJS, do checkout those.

Update: AngularJS Service Tutorial published.

Get our Articles via Email. Enter your email address.

You may also like...

147 Comments

  1. Aashita says:

    Hi,

    Can you explain how to fetch and display data from remote database server using AngularJS?

    And how to use web service in AngularJS Application?

    • Gulam Simnani says:

      Hi Aashita,
      It is not possible without node.js for server interaction. and in angularjs we can only use rest services.

      • Shubham Varshney says:

        Can it be done using php? if Yes can u Provide some help?

        • Amanpreet Singh says:

          Try enabling Odata API for your database, that allows it to be accessed via REST api.
          Then you connect to it using $http service in Angular app.

  2. Name says:

    Amazing explanation and honestly, these detailed are not mentioned in the payed technical subscription that I currently have. Keep it up.

  3. Daniel says:

    Thank you !
    Very nice article. It is my first one on angularJS.
    Now i think i have the essential to go further.

  4. keshah says:

    Hi I am learning AngularJS. I want to display user detail information on second page based on selected user from first page. I want to pass userid to second page data file. I am using JSON data file and later will work on API. Can you please explain how to do the same?

  5. Bala says:

    There are very less good articles on AngularJS, probably good videos out there on Youtube. But sometimes you just need something to read. This is one of the good series post.

    Thanks again Viral!

  6. alanb says:

    Another excellent introductory tutorial. You should write a book on AngularJs for beginners.
    Please do some further articles on services or testing. Many thanks.

  7. prem says:

    this is very fantastic topic provide by u.it is very usefull for us.i m requesting to u please post a topic related to custom directive as well as related to use of services in angular.js
    thanks

  8. anaida says:

    I have a top navigation and on selection of one of it I have a page with tabstrip( in view- partials page) . I want to change content inside partial page. Can you please help with a simple example?

  9. Emad says:

    It was simply amazing and clear. Was super useful for me.

  10. Kevin Gill says:

    Thanks for posting this information – I was digging around in the docs and other online resources to find what is going wrong in my controllers – your tutorial is just what I needed – very susinct.

  11. jose says:

    Stopped working with later versions of Angular.js, please update accordingly

  12. sajid ali says:

    Nice post Viral. Keep Going…

  13. satyam says:

    Can you suggest me how to create the web application structure with angular js 12.6

  14. asasa says:

    I want to download the sample code of this example…

  15. Raveendra says:

    Nice topic. I had a problem with the code, the same code is not worked for me. Later I made minor change to the code, then it works fine for me.
    Changes are
    1. downloaded the angular-route.min.js from angularjs.org and made available for .html page
    2. passed ‘ngRoute’, the dependency while defining the module, like this
    var sampleApp = angular.module(‘sampleApp’, [‘ngRoute’]);

    I am not sure how the Demo link is working without above changes.
    thanks

    • Jeremy says:

      Yeah, I had to do the same thing. Maybe angular-route was included in the version he used for the example, but is now a separate download in later versions.

  16. don says:

    Great article.

    well done.

  17. Code Lover says:

    Absolutely perfect. Thank you very much for the great explanation. Keep up good work.

  18. Angad says:

    Hi, I am trying to use angularjs routeprovider and facing some problem.
    When i click on the hyperlinks, it changes the url but do not load the specified html files.

    <section class="notification">
    	<div id="header">
    		<div class="container">
    			<div class="row">
    				<div class="span8">
    					<h1 class="theme--primary">Notification</h1>
    				</div>
    				<div class="span4  hidden-phone">
    					<a class="styleColor1 hidden-phone"
    						href="http://optimum.custhelp.com/app/chat/chat_launch"><span
    						class="txt"><i class="icon-comments"></i>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>
    								Live chat</strong></span></a> <a class="styleColor1 .margin-0" href="#"><span
    						class="txt"><i class="icon-twitter"></i>
    							&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>@OptimumHelp</strong></span></a>
    				</div>
    			</div>
    		</div>
    	</div>
    	<!-- Responsive Grid Example -->
    
    
    	<div class="container top-section-padding">
    		<h2>{{notification.label}}</h2>
    		<h3>{{notification.summary}}</h3>
    		<div id={{vNotification[0].id}}>Notification type A</div>
    		<div id={{vNotification[1].id}}>Notification type B</div>
    		<div id={{vNotification[2].id}}>Notification type C</div>
    		
    		<div>
    			<div>
    				<ul>
    					<li><a href="#AddNewOrder">Add New Order</a></li>
    					<li><a href="#ShowOrders">Show Order</a></li>
    				</ul>
    			</div>
    			<div>
    				<div ng-view></div>
    			</div>
    		</div>
    		
    		<div ng-bind-html="notification.body"></div>
    		
    		<a cta-arrow-link class="primary"
    			href="/support/alerts-and-notifications">All alerts and
    			notifications&nbsp;</a>
    	</div>
    </section>
    

    var notifyMe = angular.module('notification', [ 'config', 'ngSanitize',
    		'ctaArrowLink' ]);
    
    notifyMe.controller('NotificationCtrl', [ '$location', '$http', 'Config',
    		'$scope', function($location, $http, Config, $scope, $routeProvider) {
    
    		} ]);
    
    notifyMe.config([ '$routeProvider', function($routeProvider) {	
    	$routeProvider.when('/AddNewOrder', {
    		templateUrl : 'add_order.html',
    		controller : 'AddOrderController'
    	}).when('/ShowOrders', {
    		templateUrl : 'show_orders.html',
    		controller : 'ShowOrdersController'
    	});
    } ]);
    
    notifyMe.controller('AddOrderController', function($scope) {
    
    	$scope.message = 'This is Add new order screen';
    
    });
    
    notifyMe.controller('ShowOrdersController', function($scope) {
    
    	$scope.message = 'This is Show orders screen';
    
    });
    
    AddOrderController.$inject = ['$scope'];
    
    ShowOrdersController.$inject = ['$scope'];
    

    • Hi Angad, You seems to have missed the notifyMe.config definition for NotificationCtrl. You must define mapping to $routeProvider: $routeProvider.when('/Notification', {templateUrl: 'notification.html', controller: 'NotificationCtrl'})

    • Winset says:

      Hi Angad, I also facing same issue. did u get solution on this?

    • Tarak says:

      I think u need to include the angular-route.js for latest version of angularjs in head section like the this

  19. neha agrawal says:

    This is the best tutorial I have found on internet on Angualr js for beginners. You write really well!! I came here with so many doubts but now everything is crystal clear after reading your blog. Keep up the good work!!

  20. Anand George says:

    Nice set of tutorials. The examples don’t seem to work with current versions of angular. Any modifications that could help.

  21. Interesting says:

    Explaining why ngroute was removed.
    https://github.com/angular/angular.js/issues/2804

  22. dobelf says:

    thank you for this useful tutorial viral ^_^. please add more tutorial about angularjs, it is interesting to learn about this with your tutorial.

  23. alle says:

    One of the Awesome explanation I have seen in these days on Angular JS.. You are rocking.. keep good work up Thanks.

  24. MS says:

    Very nice article Viral. I’m new to AngularJS and your posts are very practical base,keep posting on same.

  25. Michal says:

    Thanks man, that’s a very good tutorial. Helped me understand a few issues. Keep on rockin’!

  26. Vik says:

    Amazing tut.!!!!

    I would like to know, if i can separate those templates – into separate js files, in order to keep my html page neater.

  27. Vinod says:

    Ah great at last some tutorial which can bore through my thick skull…!!
    Thx :)

  28. Hasan Yousef says:

    Hi Viral,
    I downloaded your plunker:

    but once I run it from my PC, I got the URL like this, and nothing changed or displayed in the page
    “file:///C:/Users/Home/Downloads/ng-route/index.html#/ShowOrder/1234”

  29. Smita says:

    Hi Viral,

    Very Nice tutorial.Happy to say that I know angular.js .
    Thanks A ton.

  30. Excellent explanation, thank you very much.
    Much much more easier than Angular docs.

    Have nice day!

  31. david yang says:

    Very nice tutorial . Thank you.

  32. Gopal Krishna says:

    Hi Viral,

    Nice Explanation, but i’m facing the following issue:
    Failed to load resource: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘null’ is therefore not allowed access.

    Any help on this is greatly appreciated.

    Thanks
    GK

  33. Adeel Hussain says:

    Thanks for such a nice tutorial, honestly i had not seen such a nice tutorial…

  34. Ashok says:

    When i click on the hyperlinks, it changes the url but do not load the specified html files. i downloaded the code from plunker..can you help me please.

  35. Viet Nguyen says:

    Hello VP,

    Thank you so much for this useful tutorial.

    But when I’m trying the code with the newest version of Angular (AngularJS v1.3.0-beta.5), it does not work. If I use that code with version 1.0.7 as in this tutorial, it works fine.

    Can you please show me what’s wrong with version 1.3.0.

    Thanks.

  36. Rajasekhar says:

    Good tutorial. But the first example in routing you have shown is not working. when iam clicking the link url is changing but it is not displaying the contents in the html files…

  37. tutor says:

    Good one..But what If I have to click a button and open the file in pdf format using angularjs? how would u achieve that?

  38. Pirate says:

    Hi,
    I tried your example (the first one where the links should only change the context using 2 different simple views) but for some strange reason it does not work at all.
    Either the views do not get loaded or the routing does not work and I dont know what’s the reason.
    I also tried the other examples, some famouse tutorials and their demos which I downloaded and they also don’t work.
    Any idea?

  39. Durgesh says:

    Hi Viral i did whatever you did but when i run it my browser(offline), it doesn’t work does it require the server to load it on and then run it.? Please help me to understand this..Thanks

    here is my html code View-

    Ng-Route

    <!—->

    Add New Order
    Show Order

    and here is your angular code-

    var sampleApp = angular.module(‘sampleApp’, []);

    //Define Routing for app
    //Uri /AddNewOrder -> template add_order.html and Controller AddOrderController
    //Uri /ShowOrders -> template show_orders.html and Controller AddOrderController

    sampleApp.config([‘$routeProvider’, function($routeProvider) {
    $routeProvider.
    .when(‘/AddNewOrder’, {
    templateUrl: ‘partials/add_order.html’,
    controller: ‘AddOrderController’
    }).

    .when(‘/ShowOrders’, {
    templateUrl: ‘partials/show_orders.html’,
    controller: ‘ShowOrdersController’
    }).
    otherwise({
    redirectTo: ‘/AddNewOrder’
    });

    }]);

    sampleApp.controller(‘AddOrderController’, function($scope){
    $scope.message = ‘This is add New Order Screen’;
    });

    sampleApp.controller(‘ShowOrdersController’, function($scope){
    $scope.message = ‘This is Show Order Screen’;
    });

    let me know am i doing something wrong or is it something else.?

  40. Durgesh says:

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Ng-Route</title>
    <!--[if IE]>
      <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    
    <link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
    
    <!--<script href="js/modernizr_2.7.2.js"></script>-->
    </head>
    
    <body ng-app="sampleApp">
    <div class="container">
            <div class="row">
            <div class="col-md-3">
                <ul class="nav">
                    <li><a href="#AddNewOrder"> Add New Order </a></li>
                    <li><a href="#ShowOrders"> Show Order </a></li>
                </ul>
            </div>
            <div class="col-md-9">
                <div ng-view></div>
            </div>
            </div>
     </div>
    
    
    <!-- For angularJS use only -->
    <script src="js/angular.min.js"></script>
    <script src="app.js"></script>
    </body>
    </html>
    
    

    • saurabh mahajan says:

      Hi Durgesh,

      I also face the same problem.
      I include angularroute.js after the angular.js
      then it works fine for me.

  41. Aahedi says:

    sampleApp.controller('AddOrderController', function($scope) {
         
        $scope.message = 'This is Add new order screen';
         
    });

    Anyone help me, howto change:

    $scope.message = 'This is Add new order screen' 

    become TAG HTML or get content of page.html??

  42. aysos says:

    they don’t work

    because : Cross origin requests are only supported for HTTP.

    What is the solution ?

  43. saifulmasud says:

    Step by Step explanation and very understandable article for those are thinking to grab Angular JS.

  44. Matt says:

    Thank you for putting this together, easy to follow and worked great for me! I did have to make a minor tweak… probably because i’m on Ubuntu 14.04… Regarding nodejs, the ‘node’ namespace has been reserved for an unrelated project, so node has been renamed to nodejs on ubuntu. I was able to get around the issue by installing nodejs and then creating a simlink between the node and nodejs folders. Thanks for sharing!

  45. Swapna says:

    Hi,

    I tried the sample provided for routing but I run into an error on the Chrome console on clicking the link, saying “XMLHttpRequest cannot load file:///path/views/add_order.html. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘null’ is therefore not allowed access. ”

    Can you please help resolve this.

  46. aahedi says:

    sampleApp.controller(‘AddOrderController’, function($scope) {

    $scope.message = ‘This is Add new order screen’;

    });

    Anyone help me, howto change: $scope.message = ‘This is Add new order screen’ become TAG HTML or get content of page.html??

  47. Tishya says:

    Hi Viral,

    I’m working with routing in angular JS. I have a large application which comprises 3-4 modules.
    Is it possible for me to route from one page (in module A) to another page (in module B) and exchange data across these modules as well? If so, how can this be done?
    If I’m not wrong, this would imply using different ng-app for the ng-view.

  48. Igor says:

    Very nice article Viral. I’m new to AngularJS and your posts are very practical base,keep posting on same.

  49. SunJian says:

    Nice article, there is one thing we shoule notice, after we finished the sample 1, most people will do the sample 2, but when we do sample ,we should notice as follows: one is templates/show_orders.html, two is templates/show_order.html’,different html

    // sample 1, templates/show_orders.html’
    when(‘/ShowOrders’, {
    templateUrl: ‘templates/show_orders.html’,
    controller: ‘ShowOrdersController’
    }).

    sample 2:templates/show_order.html
    when(‘/ShowOrder/:orderId’, {
    templateUrl: ‘templates/show_order.html’,
    controller: ‘ShowOrderController’
    });

  50. Bharath says:

    Hi
    Below is my sample code. link not working. can you help me what I did wrong.

    <!DOCTYPE html>
    <html ng-app='sampApp'>
    	<head>
    		<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
    		<script src="angular-route.min.js"></script>
    	</head>
    	<style>
    		li{
    			padding :10px;
    			display :inline;
    		}
    	</style>
    
    	<Ul>
    		<li><a href="#UserReq"> User Registration</a> </li>
    		<li><a href="#AboutUs"> About Us </a></li>
    		<li> <a href="#Contactus"> Contact Us </a> </li>
    	</ul>
    	<div ng-controller='myController'>
    		Angular Js Test Msg : {{message}}
    	</div>
    	 <div class="col-md-9">
    	        <div ng-view></div>
    	        </div>
    	 </div>
    
    	<script type='text/ng-template' id='userReq.html'>
    		<h1> User Registration form </h1>
    	</script>
    	<script type='text/ng-template' id='aboutus.html'>
    		<h1> About us html </h1>
    	</script>
    	<script type='text/ng-template' id='contactus.html'>
    		<h1> Contact us Html </h1>
    	</script>
    
    	<script>
    			var sampApp =angular.module('sampApp', []);
    
    			sampApp.controller('myController',function($scope)
    			{
    				$scope.message =' Angular Js is Working';
    			});
    			sampApp.config(['$routeProvider',function($routeProvider)
    						{
    							$routeProvider.when('/UserReq',{
    							templateUrl :'/userReq.html'
    							}).
    							when('/AboutUs',{
    								templateUrl :'/aboutus.html'
    							}).when('/Contactus',{
    							templateUrl :'/contactus.html'
    							}).
    							otherwise
    							({
    								redirectTo :'/xxxxx.html'
    							});
    			}]);
    	</script>
    </html>
    

  51. Riyas Ebrahim says:

    good article..this helped me a lot…thanks…keep going Viral…

  52. chetan says:

    I have one problem using your structure , I am using your code for the routeing.like below code,
    But I have problem for the login page. login page has no lefttemplate,footertemplate,headertemplate, How we can set for this type of the code structure for login page with out header/footer/left section .

    .provider(‘myPageCtx’, function () {

    var defaultCtx = {
    title: ”,
    //headerUrl: ‘partials/default-header.tmpl.html’,
    headerUrl: ‘partials/default-header.tmpl.html’,
    leftUrl: ‘partials/default-leftnav.tmpl.html’,
    footerUrl: ‘partials/default-footer.tmpl.html’,
    };

    var currentCtx = angular.copy(defaultCtx);

    return {

    $get: function ($rootScope) {
    $rootScope.$on(‘$locationChangeStart’, function () {
    angular.extend(currentCtx, defaultCtx);
    });

    return currentCtx;
    }
    };
    })

    .config(function ($routeProvider) {

    $routeProvider.when(‘/login’, {
    templateUrl: ‘partials/login.html’
    });

    $routeProvider.when(‘/view1’, {
    templateUrl: ‘partials/partial1.html’
    });
    $routeProvider.otherwise({
    redirectTo: ”
    });

    });

    When i try to add login page without header/footer , it is not showing properly . I comment out lefturl , it is not available for all pages. if i put lefturl/footerurl/headerurl in the login config box, and remove out the lefturl/headerurl/footerurl from the provider section , it is not seen for all the pages and login pages also.

    How to set login page so we can display without left/header/footer for the login page. And other pages it is seen left/header/footer url to add it(i.e show left/header/footer section there)..

    $routeProvider.when(‘/login’, {

    //headerUrl: ‘partials/default-header.tmpl.html’,
    headerUrl: ‘partials/default-header.tmpl.html’,
    leftUrl: ‘partials/default-leftnav.tmpl.html’,
    footerUrl: ‘partials/default-footer.tmpl.html’,
    templateUrl: ‘partials/login.html’
    });

  53. Hey Patel,

    Thanks for nice tutorial to get started with $routeProvider.

    Thanks,
    Ravi

  54. youhammi says:

    thanks a lot for this good article

  55. _24_ says:

    hi sir,

    can you help me on my delete function?
    i love your tutorial..

    tnx

  56. _24_ says:

    $scope.delete = function (models){

    for (i in $scope.results){

    if ($scope.results[i].id == clientId ){
    $scope.results.splice(i , 1);

    }
    }

    yes

  57. Mahesh says:

    var sampleApp = angular.module(‘phonecatApp’, [‘ngRoute’]);
    I came to know after googling, ngRoute required in the above statement for angular 1.1.6 or later
    Thanks for the tutorial Viral Patel you really rocks

    • Manjit says:

      This is also required

  58. Ronan says:

    Many thanks for this article. I read that there is also a UIRouter module that we can use to adress routing in AngularJS.

  59. Shehab says:

    You are wonderful…….your articles helped me alot :)

  60. Paul Fortin says:

    To often articles on new technologies are written for the already initiated and riddled full of that technologies special language which makes that article useless to learn the basic concepts of that technology. I have read all your Angular JS articles and some of the others and I think they are well written and written in a common language that all programmers can understand – this allows us to learn the technology.

    Thanks for your great work!

    Paul

    • Thanks a lot Paul.. am really glad you liked these tutorials.

  61. Prasobh says:

    I’ve gone through your articles about angular js and are really great..what are all the script files that i need to download for implementing all the angular js functionalities?I would like to implement everything locally and so that iam not actually giving reference to the link in the script’s source(the link you are mentioned) attribute.Please help me with the script files
    Thanks

  62. (Re: 4. Add Custom Data to RouteProvider)

    Will it still work if the controller is not common between the two routes? I mean your example show intra-controller communication, can we have inter-controller communication using custom data feature?

  63. Andrew Chan says:

    Great article. Very well written and clearly explained.

    Thanks alot!

  64. Ravichandran Jayaramegowda says:

    Hi,

    It is not working for version “1.1.0” and above. Please suggest.

    Thanks,
    Ravi

  65. Sims says:

    Thanks alot for ur nice turtorial Viral…..
    Can u please put tutorials on tagging pictures or videos and we would be able to save that tags or can be deleted when needed.
    [on-tag-added=”{expression}”] . we can use this but can u explain how it is possible?…

  66. robert says:

    Thanks.
    was so helpful ;)

  67. Jorge says:

    Don forget to include ngRoute in your module as well as including the route.js in your head. It is an external module now in AngularJS. Otherwise, this whole thing won’t work!

    var sampleApp = angular.module('sampleApp', ['ngRoute']);

    • Sagar Mali says:

      Hi Jorge,

      I agree with you, i have implemented this scenario.
      Can you please tell me
      > why is it so ?
      > how can i add ngAnimate with ngRoute?

    • Hi Jorge,
      letscatchup.net this is my job portal , and I want to add two more page in my home page career and blogs. but my link is not working when i click on career or blog it came like shadow (black) page

      please guide me

    • Lakhwinder says:

      Thanks Jorge, it resolved the issue at my end also.
      and thanks Viral for a wonderful article for starters.

  68. Anna says:

    Why would you use routing instead of a directive?

  69. giriswamy says:

    nice

  70. Jayesh Patel says:

    Hi Viral,
    Great job…the level of explanation with Simple words … highly appreciable.
    if you can add one keyword to your code can help starters of Angular JS.

    var sampleApp = angular.module('sampleApp', ['ngRoute']); 


    “ngRoute” is missing, due to which when I copy paste your code it was giving error.

    Thanks for developing my interest on learning new technology.

  71. sunny says:

    You are wonderful…….your articles helped me alot :)

  72. John says:

    Well thats awesome! Best start for Routing. Thank you :)

  73. Fabian says:

    Awesome tutorial, thank you for taking the time of doing this article!!!!

  74. Vineet says:

    Viral,

    Thanks for a great (and thorough) tutorial on this subject. I am pretty new to Javascript and AngularJS and something that I couldn’t quite understand was the argument to the .config. According to the angular.Module, config method takes configFn as a parameter, yet your example shows [‘$routeProvider’, function …] as an arg. I was wondering what does the square brackets mean here?

    BTW, I am going through your other articles as well on AngularJS. Appreciate them all.

  75. thank u sir , very helpful article

  76. Anil says:

    Really a cool tutorial, i got to learn a lot by this tutorial. Am new to angular, if we can some more working examples.
    Thanks

  77. santosh shimpi says:

    Thanks for the article, i have 1 problem

    when running the application , it changes url in browser to ‘http://localhost:8080’

    Could you please inform on this

  78. Denis says:

    Big thanks for this tutorial, it a lot more clear than oficial one and certainly better than dry documentation.

  79. thomas says:

    Nice tutorial. Thanks a lot.

  80. Aparna says:

    Thanks buddy, it helped a lot.

  81. Rajesh says:

    hi Viral,

    i want to load multiple html’s along with controller’s in to single html or single .
    Please let me if we have any way.

    Thanks in advance.

  82. Jhondoe says:

    Easy, basic and really power for begin point of learn, THANKS!

  83. sourav bhusan says:

    Hi, I want to make user login using drupal database. I don’t have any idea for this. I new in AngularJs. So can you help me?

  84. venkatraja says:

    Sir,
    Your angularjs tutorials are very fine. Why you not cover Directives in this tutorial. This is very useful for us. Thanks for your service.
    By,
    K.T.Venkat Raja

  85. Ajit Kumar says:

    sir,
    when i am using the latest angular in this code its not working.. Please help me find a solution

    used version

    latest version

  86. Tridip says:

    which code we need to stored in app.js ?

    you could provide a source code download link as a result people can download and run the apps in their pc. thanks

  87. Chris says:

    Hi Viral,
    I just want to thank you for a great tutorial. This has helped me a great deal.

  88. shiva says:

    I have play framework (java) providing services. Planning to have Angularjs for UI. Both Angular and Play do have their own routes. I want the Angularjs making calls to Play services through Angularjs controllers. How do I make these routers work in this fashion? My application is going to Play and gives up saying that route not found.

    Any examples are appreciated.

  89. sachin verma says:

    very nice tutorial…as u always did great things….keep helping.. :)

  90. Vijay Soni says:

    i would like to thanks for this artical… pls keep writing…

  91. Jyotirmoy Pan says:

    There are several tutorials on angular but you have explained the concepts with much ease an clarity. Great going. You can also provide some plunkr examples, it would be great if we can play with some of the features giving more clarity.

  92. Johnathon Deniz says:

    Like many others, I also just wanted to say thanks on such a simple, yet informative, tutorial

  93. dipti says:

    Thanx for the tutorial!!!!!

  94. Pankaj says:

    nice explanation…thanks

  95. Samata Rao says:

    Thanks a ton for publishing such an amazing article!

  96. Sunil Dandwate says:

    Great article to learn proper and understand thanks.

  97. JANAK patel says:

    Could you upload tutorial on $http , $resource $q and promises in angular js

  98. Dastagiri says:

    Good tutorial for beginners !!!!!!! Thank you!

  99. Chandru says:

    Can anybody explain me how can we implement the routing with ng-click(buttons) instead of anchor tags.

    Thanks…!!

  100. Old Man Whately says:

    Good read youngin’, helper’ed alot in figuring out this $routeProvider static viewing, unlike the Angular documentation!

  101. Vitthal says:

    Thanks Viral..keep going waiting for your next blog

  102. Dhruv says:

    Thank a lot. I like the simple way you explain thing.
    I read the other article about service and factory also.
    that was also very nice.
    One REQUEST
    WOULD U PLEASE GIVE YOUR INPUTS ON PROVIDERS AND CONFIG AND WORKING OF THE ANGULAR JS .. like which is invoked first and so on and so forth.
    Thanks again

  103. Arash Masir says:

    Thanks so much , it was so clear and useful.

  104. Glen says:

    Hi I’m new to angular. I have now understood routing. but when i click on the links (on my local system) its not working? how do i test locally? thx.

  105. Glen says:

    How to test this tutorial in local system. its now working in local system

  106. krishnan says:

    hi,

    the example of 1 . Introduction to $routeProvider – i just tried the same why you have, its not loading my templates, on click getting some error: Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.14/$injector/modulerr?p0=sampleApp&p1=Error…%2F%2FD%3A%2FKrish%2FLearning%2FAngularJS%2Fjs%2Fangular.min.js%3A38%3A135)

    is that dependency injection is must ?

  107. John says:

    Thank you for an awesome tutorial. it helped me very much.
    Your code has a bug. The links must start with ‘#/’ otherwise the browser Back button will not work. For example “#ShowOrder/1234” should be “#/ShowOrder/1234”. This is documented here. http://stackoverflow.com/questions/16967331/angular-js-browser-back-button-dosnt-work-when-routing

  108. Diep says:

    Very nice explanation!

    It helped me – an angular beginner – a lot.

  109. great post! makes seemingly complicated ng protocols a breeze :)

  110. Bhaskar says:

    @krishnan include “ngroute” in D I . let the compiler know about the dependance on ngroute which is not included in ur angular.js file.

  111. Vishal says:

    It is really useful for beginners of AngularJS..

  112. Vishal says:

    Thanks Viral..

  113. Arun says:

    Thanks. Very helpful blog as usual.

  114. amar says:

    Its an proper document ion working on live project And the beginner And knowing the Dependency of the any app

  115. Amar says:

    Its an proper document ion working on live project

  116. chaitanya says:

    how can i change views selecting the dropdownlist instead if href

    • Hi Chaitanya , here is a sample solution how to change views based on selection from dropdown.

      Templatelink1
      Templatelink1
      Orders Template

    • Ravinder Kumar says:

      Chaitanya, to change view on any event you need to write an event handler and in that event handler you need to use $location service from Angular. Pass relative path to “path” method of this service and rest will be handled by $routeProvider.

      HTML:

      Javascript:
      routingApp.controller(‘mainAppController’, function($scope,$location){
      $scope.navigate = function(){
      $location.path(‘/showList’);
      };
      });

  117. Hemanta says:

    Thanks Viral..keep going waiting for your next blog

  118. Hemanta says:

    Thanks Viral..keep going waiting for your next blog. Please prepare something on Node.js

  119. RohitSG says:

    very helpful, but u should add [‘ngRoute’] dependency at the time of creating app, as angular.module(‘myApp’,[‘ngRoute’]);

  120. Niranjan says:

    excellent explanation, keep up the good work

  121. Jackson Joseraj says:

    Thanks Viral. It was a very good article for beginners who wish get into angular.

  122. dfgs says:

    Thanks, it is a very clear tutorial

  123. shakeer says:

    Love your Post

  124. Roshan says:

    Thanks man. Simply Awesome.

  125. This is the best tutorial exercise I have found on web on Angular js for beginners. You compose truly well!! I came here with such a large number of questions however now everything is perfectly clear in the wake of perusing your web journal. Keep doing awesome!!

  126. Unnati Chauhan says:

    ITS SERIOUSLY AMAZING … THANK YOU SO MUCH……

  127. Jagdish says:

    Nice Tutorial, But your first example of both controller calling twice. :)

  128. Kareermatrix says:

    Amazing article. Thanks to you.

  129. Jo says:

    Hi Viral

    I tried your article in Notepad ++. When i run the sample1.html, i find that the links are not working for me. I have copied and padted ur code. COuld you please help on this. I stored app.js, sample1.html, add_order.html and show_order.html in my D drive. I am a beginner in Angular JS, please help

    Thanks
    Jeni

  130. saqib says:

    how Can I add path of controller.js instead of name of controller

Leave a Reply

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