Using the $routeProvider, you can specify which page to display when a user clicks a link.
Define a $routeProvider:
var app = angular.module(“myApp”, [“ngRoute”]); app.config(function($routeProvider) { $routeProvider .when(“/”, { templateUrl : “main.htm” }) .when(“/london”, { templateUrl : “london.htm” }) .when(“/paris”, { templateUrl : “paris.htm” }); }); |
Define the $routeProvider within the config method of your application. Any configurations made in this method will be executed while the application is loading.
The $routeProvider also allows you to specify a controller for each “view.”
Include controllers:
var app = angular.module(“myApp”, [“ngRoute”]); app.config(function($routeProvider) { $routeProvider .when(“/”, { templateUrl : “main.htm” }) .when(“/london”, { templateUrl : “london.htm”, controller : “londonCtrl” }) .when(“/paris”, { templateUrl : “paris.htm”, controller : “parisCtrl” }); }); app.controller(“londonCtrl”, function ($scope) { $scope.msg = “I love London”; }); app.controller(“parisCtrl”, function ($scope) { $scope.msg = “I love Paris”; }); |
The “london.htm” and “paris.htm” files are standard HTML files where you can include AngularJS expressions just like in any other HTML section of your AngularJS application.
The files are structured as follows:
london.htm
<h1>London</h1> <h3>London is the capital city of England.</h3> <p>It is the most populous city in the United Kingdom, with a metropolitan area of over 13 million inhabitants.</p> <p>{{msg}}</p> |
paris.htm
<h1>Paris</h1> <h3>Paris is the capital city of France.</h3> <p>The Paris area is one of the largest population centers in Europe, with more than 12 million inhabitants.</p> <p>{{msg}}</p> |