0

我想創建一個簡單的單頁面應用程序在使用Django + Django Rest Framework + Angularjs。成功登錄/密碼錶單後,我應該重定向到帶有聯繫人列表的頁面,在那裏我可以添加或刪除。對於我的後臺,我將使用教程從這裏http://www.django-rest-framework.org/tutorial/quickstart/,和簡單的登錄/密碼頁面看起來就像這樣單頁面應用程序Angularjs Django登錄表單

<html ng-app="myApp"> 
    <head> 
    <title></title> 
    </head> 
    <body ng-controller="AppController as ctrl"> 

     <form ng-submit="ctrl.submit()"> 
      <input type="text" ng-model="ctrl.user.username" placeholder="Enter your name"/><br/><br/> 
      <input type="text" ng-model="ctrl.user.password" placeholder="Enter your Password"/><br/><br/> 

      <input type="submit" value="Submit"> 
     </form> 

     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"> 
     </script> 
     <script> 
      angular.module('myApp', []) 
      .controller('AppController', [function() { 
       var self = this; 
       self.submit = function() { 
        console.log('Form is submitted with following user', self.user); 
      }; 
     }]); 
    </script> 
    </body> 
</html> 

而且我不明白我怎麼可以從前置式提交登錄/密碼的形式端到端的應用程序的後端?

回答

1

首先必須使用POST發送表單數據:

<form ng-submit="ctrl.submit()" method="POST"> 

然後ngResource模塊可以用來將請求發送到後端。

1:安裝角度資源。使用亭子:bower install --save angular-resource

2:添加ngResource dependencie到您的模塊定義:

angular.module('myApp', ['ngResource']) 

3:注入$resource服務到您的控制器:

.controller('AppController', ['$resource', function($resource) { 

4:使用$資源服務創建資源併發送請求

self.submit = function() { 
    // path to the login endpoint, and custom submit method to send the login data. 
    var loginResource = $resource('/api/login/', {}, {submit: {method: 'POST'}}); 
    loginResource.submit(self.user, function(response) { 
     console.log('LOGIN Success', response); 
    }, function(err) { 
     console.error('LOGIN Error', err); 
    }); 
    console.log('Form is submitted with following user', self.user); 
}; 

欲瞭解更多詳情,請訪問docs for $resource service