Reputation: 43
I have a few routes specified:
app.config(["$routeProvider", "$locationProvider", function($routeProvider, $locationProvider) {
$routeProvider.
when("/", {
templateUrl: "/ajax/home.html",
controller: "HomeController"
}).
when("/test/:id", {
templateUrl: "/ajax/test.html",
controller: "TestController",
resolve: {
data: function ($q, $http, $route) {
var deferred = $q.defer();
var params = $route.current.params;
$http({method: "GET", url: "/api/test/" + params.id + ".json"})
.success(function(data) {
deferred.resolve(data)
})
.error(function(data){
deferred.reject();
});
return deferred.promise;
}
}
});
$locationProvider.html5Mode(true);
}]);
When there is a link on another route leading to /test/x
, it works fine. It also works fine when not in HTML5 mode. However, when you navigate directly to /test/x
in HTML5 mode, the route doesn't load and none of the stuff in resolve is executed.
I've looked through much of the AngularJS documentation and still can't figure this out. plz :(
Edit: I've done more testing, and this is only for routes that have a slash in them. It doesn't seem to matter if there is a parameter (like :id
) in it or not. Going to /hello
(if that route is defined) works for all cases in both HTML5 and non-HTML5 mode. Going to something like /hello/world
always works in non-HTML5 mode and works in HTML5 mode when the route is changed from another route by clicking a link. Refreshing when on /hello/world
, going to the address bar and pressing enter or clicking a link pointing to it from another website causes it to reload the index page but not the actual route.
Upvotes: 4
Views: 4388
Reputation: 7855
Adding <base href="/" />
to the <head>
section is a fix, depending on which issue you are experiencing.
(this was the answer for me, so I wanted to make sure to make it more obvious for others that run into this)
Thanks to @user27766 for pointing it out.
Upvotes: 5
Reputation: 14991
The angular docs for the $location service state that using HTML5 mode requires you to use URL rewriting on the server side to rewrite all your links to the entry point of your application (e.g. index.html)
If you were using Apache to serve your application then you could set up a .htaccess
file like so:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^test/[0-9]+$ index.html [L]
This would redirect requests like /test/<number>
to index.html
and angular should be able to route it properly.
Upvotes: 0