首頁  >  問答  >  主體

python - angular route 与 django urls 冲突怎么解决?

app.js

var app = angular.module('app', [
    'ngResource',
    'ngRoute',
    // 'ui.bootstrap',
    // 'ngResource',
    'student',
]);

app.config(
        function(
          $locationProvider,
          $routeProvider
          ){
          $locationProvider.html5Mode({
              enabled:true
            })
          $routeProvider.
              when("/", {
                template: 'base',
              }).
              when("/student/1", {
                template: "<student-detail></student-detail>",
              }).
              otherwise({
                template: "Not Found"
              })

    });

student.js

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

app.component('studentDetail',{
        templateUrl:'studentDetail.html',
        controller: function($scope) {
        $scope.test = 'Got it.'
        }
      });

urls.py

class SimpleStaticView(TemplateView):

    def get_template_names(self):
        return [self.kwargs.get('template_name') + ".html"]

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^api/', include("students.api.urls", namespace='students-api')),

    url(r'^(?P<template_name>\w+)$', SimpleStaticView.as_view(), name='example'),
    url(r'^$', TemplateView.as_view(template_name='home.html')),
]
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    # urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

测试,当访问/base字段是出现的,说明ng-view工作 正常,但当访问/students/1时,返回django路由报错,未找到该路由。

studentDetail.html是存在的。

这是angular没获取到路由请求吗?该如何解决?谢谢。

迷茫迷茫2741 天前452

全部回覆(1)我來回復

  • 迷茫

    迷茫2017-04-18 10:34:02

    謝邀,推薦你先看一下這篇文章 - 單頁應用的核心

    開發調試時,你可以使用開發者工具,查看模板請求的實際路徑,另外Django 路由配置,你只要能匹配模板請求地址,正確返回模板文件即可。 Angular 1.x 前端部分請參考以下範例:

    Angular 1.x Demo 專案目錄結構

    views/student.module.js

    var studentModule = angular.module('student', []);
    
    studentModule.component('studentDetail',{
        templateUrl:'views/studentDetail.html', // 注意这边的路径,相对于根目录
        controller: function($scope) {
            $scope.test = 'Got it.'
        }
    });

    views/studentDetail.html

    <h4>{{test}}</h4>

    index.html

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Angular 1.x Demo</title>
        <base href="/" > <!--需根据部署后的实际路径做调整-->
        <script src="https://cdn.bootcss.com/angular.js/1.6.3/angular.min.js"></script>
        <script src="https://cdn.bootcss.com/angular.js/1.6.3/angular-route.min.js"></script>
        <script src="views/student.module.js"></script>
    </head>
    <body ng-app="app">
    <p>
        <a href="/student">Student</a>
    </p>
    <p ng-view></p>
    <script type="text/javascript">
        var app = angular.module('app', [
            'ngRoute',
            'student',
        ]);
        app.config(
                function(
                        $locationProvider,
                        $routeProvider
                ){
                    $locationProvider.html5Mode({
                        enabled:true
                    });
                    $routeProvider.
                    when("/", {
                        template: 'base',
                    }).
                    when("/student", {
                        template: "<student-detail></student-detail>",
                    }).
                    otherwise({
                        template: "Not Found"
                    })
                });
    </script>
    </body>
    </html>

    建議如果新專案使用 Angular 1.x 都要不要再使用$scope哈,好處有很多,其中一點是方便以後升級遷移,開發語言可以考慮使用 ES6 或 TypeScript。組件範例如下:

    const counter = {
      bindings: {
        count: '<'
      },
      controller() {
        this.increment = () => this.count++;
        this.decrement = () => this.count--;
      },
      template: `
        <p>
          <button ng-click="$ctrl.decrement()">-</button>
          <input ng-model="$ctrl.count">
          <button ng-click="$ctrl.increment()">+</button>
        </p>
      `
    };
    
    angular
      .module('app')
      .component('counter', counter);

    詳細可以參考,component-property-binding-input-angular-2

    另外如果有興趣的話或項目允許的話,可以考慮一下使用新版的Angular,目前最新的版本是4.0.1哈

    友情提示(題主請略過):本範例需要啟動本機伺服器哈,如果有安裝Python的話,可以在命令列執行 python -m SimpleHTTPServer

    參考資料

    • Angularjs html5mode模式路由

    • angular路由去掉的URL裡的#號

    回覆
    0
  • 取消回覆