Angular Route - Extra # in URL

2020-04-17 07:31发布

问题:

Learning some Angular - and I'm stuck on routing

Here is my angular config

var meanApp = angular.module('carz', ['ngRoute']);


meanApp.config(function($routeProvider) {
    $routeProvider
        .when('/', {
            templateUrl: 'home.html',
            controller: 'mainCtrl'
        })
        .when('/red', {
            templateUrl: 'red.html',
            controller: 'redCtrl'
        });
});

Here is are my links

<a href="#">Home</a>
<a href="#red">Red</a>

When I load up my node app I am directed to

http://localhost:8080/#!/

And I get my angular controller working as expected within the ng-view tags

But I cannot switch from one controller to the other using the links above.

If I select the red tag my URL adds an extra # becoming

http://localhost:8080/#!/#red

Note if I manually change to

http://localhost:8080/#!/red

My controller changes and it works so why am I getting the extra #

Thanks for any help

回答1:

Since AngularJS 1.6 there is a breaking change in routing:

The hash-prefix for $location hash-bang URLs has changed from the empty string "" to the bang "!".

(See https://github.com/angular/angular.js/blob/master/CHANGELOG.md)

Solution:

either start using #! Instead of # OR set up $locationProvider to accept just using #, like this:

appModule.config(['$locationProvider', function($locationProvider) {
    $locationProvider.hashPrefix('');
}]);