简体   繁体   中英

AngularJs routing not working when clicked on an anchor tag button

I created this Plunker and added a simple routing. But for some reason routing is not working. I want to redirect to #/delete when clicked on a delete button, but nothing is happening.

script.js:

var appRoot = angular.module('myNgApp', ['ngRoute', 'ui.bootstrap']);

appRoot.config([
    '$routeProvider', function ($routeProvider) {
        $routeProvider
            .when('/', { templateUrl: 'ngIndex.html', controller: 'IndexCtrl' })
            .when('/delete', { templateUrl: 'delete.html', controller: 'DeleteCtrl' })
            .otherwise({ redirectTo: '/' });
    }
]);

ngIndex.html:

<a class="btn btn-danger"  href="#/delete">Delete</a>

So it because of a change in angular 1.6 route with the hash-prefix. So instead og "" the hashprefix is now "!"

Due to aa077e8, the default hash-prefix used for $location hash-bang URLs has changed from the empty string ('') to the bang ('!'). If your application does not use HTML5 mode or is being run on browsers that do not support HTML5 mode, and you have not specified your own hash-prefix then client side URLs will now contain a ! prefix. For example, rather than mydomain.com/#/a/b/c the URL will become mydomain.com/#!/a/b/c.

If you actually want to have no hash-prefix, then you can restore the previous behavior by adding a configuration block to you application:

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

I made a similar post with possible solutions: Angular not routing properly. URL is localhost:8081/#!/#pageName

From the other post:

What to do?
1. Set HTML5mode true

$locationProvider.html5Mode(true);

and in html set base in html header:

<base href="/">

Lastly change <a ng-href="#pagename"> to

<a ng-href="pagename">

2. Go back to old behaviour from 1.5 - set hash prefix manually This will make your app work as you expect in your question.

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

In your example
To see that this is the problem you can change

$window.location.href = '#/delete';

to

$window.location.href = '#!/delete';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM