Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular routing doesn't work for controllers with same module names

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:

Directory structure for the application

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?

like image 365
kamal0808 Avatar asked Jan 06 '23 06:01

kamal0808


1 Answers

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

like image 113
Sajeetharan Avatar answered Jan 08 '23 19:01

Sajeetharan