I am trying to use Angular's routing mechanism in an app, however on clicking on element which should cause the routing I'm getting a cannot GET viewName, where viewName is any view.
This is my app.js script file:
var app = angular.module('actsapp', ['ngRoute']);
//Define Routing for app
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/student_list.html',
controller: 'StudentListController'
})
.when('/Students', {
templateUrl: 'views/student_list.html',
controller: 'StudentListController'
})
.when('/RegisterStudent', {
templateUrl: 'views/register_student.html',
controller: 'StudentRegistrationController'
});
}]);
app.controller('StudentListController', function($scope) {
$scope.message = 'This is student list screen';
});
app.controller('StudentRegistrationController', function($scope) {
$scope.message = 'This is student registration screen';
});
and this is my index.html:
<!DOCTYPE html>
<html ng-app="actsapp">
<head>
<title></title>
<link href="style/style.css" rel="stylesheet" />
<link href="style/bootstrap.css" rel="stylesheet" />
<script src="scripts/jquery-1.js"></script>
<script src="scripts/angular/angular.js"></script>
<script src="scripts/angular/angular-route.js"></script>
<script src="scripts/angular/app.js"></script>
</head>
<body>
<div class="header">
<div class="heading_wrap">
<h1>Student Registration Form</h1>
</div>
</div>
<div class="nav-wrap">
<ul class="nav nav-acts-pills nav-stacked ">
<li class="active">
<a href="/Students">Student List</a>
</li>
<li>
<a href="/RegisterStudent">Add Student</a>
</li>
<li>
<a>Add Students (By School)</a>
</li>
</ul>
</div>
<div ng-view="" class="content-wrap" style="float:left;">
</div>
</body>
</html>
Any suggestions on how to fix this are much more than welcome. I based my work on the latest version of the ngRoute documentation. Thank you.
You need to add the #
like below to work the routing:
<li class="active">
<a href="#/Students">Student List</a> // add #
</li>
<li>
<a href="#/RegisterStudent">Add Student</a> // add #
</li>
And in the .js file, templateUrl
should be like: /views/student_list.html
.
However, if you need routes without #
, you need to add $locationProvider.html5Mode(true);
. Check the example here to learn how to avoid using #
. Also, see this. The demo says that:
app.config(['$routeProvider',
function($routeProvider,$locationProvider) {
$routeProvider
.when('/', {
templateUrl: '/views/student_list.html', // urls should be like this
controller: 'StudentListController'
})
.when('/Students', {
templateUrl: '/views/student_list.html', // urls should be like this
controller: 'StudentListController'
})
.when('/RegisterStudent', {
templateUrl: '/views/register_student.html', // urls should be like this
controller: 'StudentRegistrationController'
});
$locationProvider.html5Mode(true);
}]); ]
In the view :
<li class="active">
<a href="/Students">Student List</a>
</li>
<li>
<a href="/RegisterStudent">Add Student</a>
</li>