单页应用程序Angularjs Django登录表单



我正在尝试创建一个简单的单页应用程序,使用Django+Django Rest Framework+Angularjs。在成功登录/密码表单后,我应该重定向到带有联系人列表的页面,在那里我可以添加或删除它。对于我的后端,我将使用这里的教程http://www.django-rest-framework.org/tutorial/quickstart/,和简单的登录/密码页面将看起来像这个

<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> 

我不明白如何从应用程序的前端向后端提交登录/密码表单?

首先必须使用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:使用$resource服务创建资源并发送请求

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);
};

有关更多详细信息,请访问$resource服务的文档