这个例子可以帮助你更好地理解 $routeProvider 和 $locationProvider。
我看到的唯一问题是没有正确加载相关链接和模板。
from the docs regarding HTML5 mode
请务必检查所有相对链接、图像、脚本等。您必须在主 html 文件 () 的头部指定 url 基址,或者必须在任何地方使用绝对 url(以 / 开头),因为相对 url 将使用文档的初始绝对 url 解析为绝对 url,这通常与应用程序的根目录不同。
在您的情况下,您可以在 href 属性中添加正斜杠 / ($location.path 会自动执行此操作),也可以在配置路由时添加到 templateUrl。这样可以避免像 example.com/tags/another 这样的路由,并确保模板正确加载。
这是一个有效的例子:
<div>
<a href="/">Home</a> |
<a href="/another">another</a> |
<a href="/tags/1">tags/1</a>
</div>
<div ng-view></div>
和
app.config(function($locationProvider, $routeProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/', {
templateUrl: '/partials/template1.html',
controller: 'ctrl1'
})
.when('/tags/:tagId', {
templateUrl: '/partials/template2.html',
controller: 'ctrl2'
})
.when('/another', {
templateUrl: '/partials/template1.html',
controller: 'ctrl1'
})
.otherwise({ redirectTo: '/' });
});
如果使用 Chrome,则需要从服务器运行。