对于一个项目,我在后端使用 Django,在前端使用 AngularJs。
基本上,我想要的是仅当 url 以 projectkeeper/
开头时运行 Angular 应用程序。
换句话说,假设我的网站是 example.com。我希望 Angular 应用程序针对 URL example.com/projectkeeper/dashboard/
、example.com/projectkeeper/projects/
等运行,但不是在 example.com/about/
.
希望我已经说清楚了。无论如何,为了做到这一点,我正在用我的代码做以下事情:
urls.py
urlpatterns = [
url(r'^projectkeeper/$', TemplateView.as_view(template_name='base.html')),
]
在模板 base.html 中,我显然引用了我的 Angular 应用程序。对于 Angular 路由,我做了以下操作:
myapp.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/dashboard/', {
title: 'Dashboard',
controller : 'DashboardController',
templateUrl : 'static/app_partials/projectkeeper/dashboard.html'
})
.otherwise({ redirectTo : '/' });
}]);
因此,理想情况下,我的想法是前往 example.com/projectkeeper/#/dashboard/
将从我的 Angular 应用程序运行 DashboardController。然而,事实并非如此,我只得到一个空页面,这意味着路由不正确。
有什么解决办法吗?正如我之前所说,我希望在 url 以 projectkeeper/
开头时仅运行 Angular 应用程序。
最佳答案
我认为你已经很接近了,几乎没有什么东西可以让它起作用(老实说,这让人难以理解,我希望我没有忘记任何东西)。
首先,您的 URL 顺序很重要,如果您在 Angular 路由之前定义某些内容,它们将首先呈现,因此请在 Angular 路由之前使用您的 django 应用程序的 url。
然后,如果你想让 Angular 知道你需要定义的子路径 <base>
在标题中标记。在你的情况下:
<base href="/projectkeeper/" />
(您也可以在所有 projectkeeper
函数中定义 where
它)。
对于 url,我会将正则表达式更改为:r'^projectkeeper/.*'
.同样,应该是您的网址列表中的最后一个。
您还会遇到其他问题,例如 {{ }}
,身份验证问题,但这些将保留不同的答案:)
关于javascript - 将 Django URL 与 AngularJs routeProvider 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42061334/