This is a simple angular app which seems to have a silly mistake in the code, I'm not quite able to figure it out. The problem lies with the routing. Clicking on the links doesn't take me to the specified template url, instead reloads the same index.html page.
However, the link in the address bar changes to:
http://localhost:8000/app/#/stats
http://localhost:8000/app/#/sports
on clicking the respective links.
index.html
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="utf-8">
<title>My AngularJS App</title>
<link rel="stylesheet" href="css/style.css"/>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers/myStats.js"></script>
<script src="js/controllers/mySports.js"></script>
</head>
<body>
<div class="container">
<a ng-href="#/stats">My Stats</a>
<a ng-href="#/sports">My Sports</a>
</div>
<div ng-view></div>
</body>
</html>
app.js
'use strict';
angular.module('myApp', ['ngRoute'])
.config(['$routeProvider', function($routeProvider){
$routeProvider
.when('/stats', {
templateUrl: 'partials/stats.html'
})
.when('/sports', {
templateUrl: 'partials/sports.html'
})
}]);
I hope there's nothing wrong with my directory structure:
EDIT:
sharing code for controllers, the problem is in the controllers. It has to do something with angular modules having same names, although this was how I was taught.
js/controllers/mySports.js
angular.module('myApp',[])
.controller('mySports',['$scope', function($scope){
console.log('just checking');
}]);
What worked: Changing module name in mySports.js from myApp to mySports, and then injecting mySports as a dependency in app.js.
Updated app.js to this:
'use strict';
angular.module('myApp', ['ngRoute','mySports'])
.config(['$routeProvider', function($routeProvider){
$routeProvider
.when('/stats', {
templateUrl: 'partials/stats.html'
})
.when('/sports', {
templateUrl: 'partials/sports.html'
controller: mySports,
})
}]);
EDIT
What still remains the question is to why change the module names of controllers and then inject as dependencies into app.js? Why not have the same module names?
You need to inject ngRoute as dependency to the application
Change
From:
angular.module('myApp', [])
To:
angular.module('myApp',['ngRoute'])
Here is the working Application
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With