guagay_wk
guagay_wk

Reputation: 28030

Why is this AngularJS routing broken when html5mode is enabled?

I would like to use AngularJS routing. I am using AngularJS-seed-master as a start and routing works by default. However, it stopped working after I enabled html5mode. Below is the html code when routing works;

  <ul class="menu">
    <li><a href="#/view1">view1</a></li>
    <li><a href="#/view2">view2</a></li>
  </ul>    
  <div ng-view></div>
  <script src="lib/angular/angular.min.js"></script>
  <script src="lib/angular/angular-route.min.js"></script>
  <script src="js/app.js"></script>
  <script src="js/services.js"></script>
  <script src="js/controllers.js"></script>
  <script src="js/filters.js"></script>
  <script src="js/directives.js"></script>

Javscript app.js code when routing works;

angular.module('myApp', [
  'ngRoute',
  'myApp.filters',
  'myApp.services',
  'myApp.directives',  
  'myApp.controllers'
]).
config(['$routeProvider', function($routeProvider) 
{
    //configuration for $routeProvider
    $routeProvider.when('/view1', {templateUrl: 'partials/partial1.html', controller: 'MyCtrl1'});
    $routeProvider.when('/view2', {templateUrl: 'partials/partial2.html', controller: 'MyCtrl2'});
    $routeProvider.otherwise({redirectTo: '/view1'});

}]) 

Then, I enabled html5mode by adding this to app.js

.config(['$locationProvider', function($locationProvider)
{        
    $locationProvider.html5Mode(true);
}]) 

It is at this point that AngularJS routing stops working. What did I do wrong? How can AngularJS routing be made to work after enabling html5Mode?

Upvotes: 0

Views: 932

Answers (1)

user2122112
user2122112

Reputation:

What you have to do is in "app.js" set the "html5mode" to true:

config(['$locationProvider', '$routeProvider', function($locationProvider, $routeProvider) {
   $locationProvider.html5Mode(true).hashPrefix('!');
   $routeProvider.otherwise({redirectTo: '/view2'});
}]);

In index.html add under header:

<head>
      <base href="/" />
      <meta name="fragment" content="!">
</head>

And change the link:

<body>
  <ul class="menu">
    <li><a href="/#!/view1">view1</a></li>
    <li><a href="/#!/view2">view2</a></li>
  </ul>
</body>

And that's it the main URL: http://localhost:8000

Will redirect to: http://localhost:8000/view1

And link will work showing sexy address.

Upvotes: 1

Related Questions