Below is the code for AngularJS Route Example.
In the above example, First, AngularJS routes library file is created. Then, a user declares a dependency to the AngularJS Route Module in js file.
[html]
<!DOCTYPE html>
<html lang="en">
<head>
<title>AngularJS Routes example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular-route.min.js"></script>
</head>
<body ng-app="spApp">
<div><a href="#/route-1">Route 1</a></div>
<div><a href="#/route-2">Route 2</a></div>
<div ng-view></div>
</body>
</html>
[/html]
Configuring the $routeProvider
[javascript]
var module = angular.module("spApp", ['ngRoute']);
module.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/route-1', {
templateUrl: 'template-1.html',
controller: 'SpController'
}).
when('/route-2', {
templateUrl: 'template-2.html',
controller: 'SPController'
}).
otherwise({
redirectTo: '/'
});
}]);
module.controller("SpController", function($scope) {
})
[/javascript]
- Under config of
spApp
module, $routeProvider
is characterized as a function, utilizing key as '$routeProvider
'.
- The
$routeProvider
can be configured via calls to the when()
and otherwise()
functions. The when()
function takes route path and JavaScript object as parameters.
$routeProvider.when
defines a url "
/route-1
", which then is mapped to "
template-1.html
".
template-1.html
has to be there in the similar path as of html main page. If html page is not defined, then default view will be set.
Controller is utilized to set the corresponding controller for the view.