Willshaw Media Willshaw Media - 4 months ago 7
AngularJS Question

AngularJS subdirectory routing not working, with <base> tag applied

I've got an incredibly simple AngularJS template, I'm trying to get routing to work but when I load the page I'm just seeing the H1 tag from my

index.html
.

My app is in a sub directory,
/angular-route/
, and I know that the partials exist, I can visit
/angular-route/partials/interest.html
and the page renders fine.

Have I missed something really basic here?

<html>
<head ng-app="myApp">
<title>AngularJS Routing</title>
<base href="/angular-route/" />
</head>
<body>

<h1>AngularJS Routing</h1>

<div ng-view></div>

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>

<script>
'use strict';

var myApp = angular.module('myApp', []).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/interest', {
templateUrl: 'partials/interest.html',
controller: 'InterestCtrl'
}).
when('/catalogue', {
templateUrl: 'partials/catalogue.html',
controller: 'CatalogueCtrl'
}).
otherwise({redirectTo: '/interest'});
}]);

myApp.controller('InterestCtrl', function($scope, $routeParams) {
console.log('InterestCtrl');
});
myApp.controller('CatalogueCtrl', function($scope, $routeParams) {
console.log('CatalogueCtrl');
});
</script>




Answer

Beside the base tag, which you will need, you've also placed the ng-app directive on wrong element (head). In your code, the Application is initialized only inside the header. Rest of the HTML is ignored by Angular.

WORKING PLUNKER

<html ng-app="myApp">
<head>
  <title>AngularJS Routing</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <script type="text/ng-template" id="partials/interest.html">
    <h2>Inereset</h2> 
  </script>
  <script type="text/ng-template" id="partials/catalogue.html">
    <h2>Catalogue</h2> 
  </script>
</head>
<body>

  <h1>AngularJS Routing</h1>

  <ul>
    <li><a href="#/interest">Interest</a></li>
    <li><a href="#/catalogue">Catalogue</a></li>
  </ul>

  <div ng-view></div>

  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>

  <script>
      'use strict';

      var myApp = angular.module('myApp', []).
        config(['$routeProvider', function($routeProvider) {
          $routeProvider.
            when('/interest', {
              templateUrl: 'partials/interest.html',   
              controller: 'InterestCtrl'
            }).
            when('/catalogue', {
              templateUrl: 'partials/catalogue.html', 
              controller: 'CatalogueCtrl'
            }).
            otherwise({redirectTo: '/interest'});
      }]);

      myApp.controller('InterestCtrl', function($scope, $routeParams) {
        console.log('InterestCtrl');
      });
      myApp.controller('CatalogueCtrl', function($scope, $routeParams) {
        console.log('CatalogueCtrl');
      });
  </script>
</body>
</html