简体   繁体   中英

AngularJs Routes and Refreshing

Routes is what I am using in AngularJs to load dynamic content through an ajax calls asynchronously. This is how I do that:

var $app = angular.module('app', ['ngRoute']);

$app.config(["$routeProvider", "$locationProvider", function ($routeProvider, $locationProvider) {
  $routeProvider
    .when("/pop", {controller: "popCtrl", templateUrl: "partials/pop_test.html"})
    .when("/dashboard", {controller: "dashBoardCtrl", templateUrl: "partials/dashboard.html"})
    .otherwise({redirectTo: "/"})

    $locationProvider.html5Mode(true);
}])

I also have a mini nav set up so that when I click on my links it loads those partials through the templatrUrl parameter

   <ul>
        <li><a href="/">Home</a></li>
        <li><a href="/pop">Pop</a></li>
        <li><a href="/dashboard">Dashboard</a></li>
   </ul>

This is all working great, when I click on my links it loaded the content I have set up in pop_test.html and dashboard.html

Now the problem that I am having.

When you click on the link for lets say dashboard the content loads just fine through ng-view and the routes work great BUT if the user reloads or refreshes the page and you're on lets say localhost/dashboard it will actually try to go to that link and locate a file named after whatever you have after / which in this case is a directory called dashboard.

So how can I make it so when the user refreshes or reloads the page he doesn't actually reload the /dashboard page therefor not getting a server error page not found.

As Alberto mentioned, the server needs to know what to do. In Angular's case, everything needs to be routed through the index.html when using $locationProvider.html5Mode(true); otherwise you'll run into what you are now.

To fix this you need to add a Server Rewrite rule which you can find an explanation of it, along with the different server versions, in ui-router's docs here .

You can also add a .htaccess file with the rewrite rules for index.html like so:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]

RewriteRule ^(.*) /index.html [NC,L]

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