AngularJS - 如何将表单提交给服务器上的控制器? [英] AngularJS - How do I submit a form to a controller on the server?

查看:71
本文介绍了AngularJS - 如何将表单提交给服务器上的控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

AngularJS网站上的食谱形式示例仅保存客户端上的状态。如何提交到服务器?

The cookbook form examples on the AngularJS site only save the state on the client. How do I submit to the server?

或者,我如何使用jQuery的 form.submit() ng中的表单:click =save()函数?

Alternatively, how do I use jQuery's form.submit() on the form in the ng:click="save()" function?

编辑 - 找到2种方法来执行此操作(我还删除了之前粘贴的HTML标记 - 只需参考源代码的高级表格cookbook示例)

Edit - Found 2 ways to do this ( I also removed the HTML markup I pasted before - just refer to the advanced form cookbook example for the source)


  1. http://webpac2.rot13.org:3000/conference/Work (作者:Dobrica Pavlinusic)使用资源以AngsonJS方式将数据以JSON格式发送到服务器。我在服务器端遇到了问题 - AngularJS发送它很好但是grails正在破坏它(根据firebug和请求内容长度)。我需要更多地研究这个问题。如何更改资源方法的角度内容类型,如 $ save()

  1. http://webpac2.rot13.org:3000/conference/Work (by Dobrica Pavlinusic) to go the AngularJS way using a resource to send the data to the server in JSON format. I had issues with that on the server side - AngularJS was sending it fine but grails were mangling it (according to firebug and request content-length). I need to look into this more. How do I change the content-type in angular for a resource method like $save()?

将表单放入并使用提交按钮。由于我没有使用单页Web应用程序,因此我使用了这种方法。大多数验证都在客户端上,在服务器上还有一些验证对我来说已经足够了。

Put a form in and use a submit button. Since I am not doing a single page web app, I used this method. Most validations were on the client and a few more on the server which was sufficient for me.

只需将此放在此处,以便其他人可以将其用于可能的解决方案和最佳方法。

Just putting this here so that someone else can use this for possible solutions and best approach.

推荐答案

注意,严格分离视图(您的html模板)和逻辑(你的JS代码) - 主要是因为可测试性。

Note, there is strict separation of view (your html template) and logic (your JS code) - mainly because of testability.

正确的方法是使用 $ resource 将模型发送到服务器(对于REST)或低级 $ http 。而不是在模板中完成工作。

The right way is to just send your model to the server, using $resource (for REST) or low level $http. Instead of doing the job in the template.

简单示例 - HTML模板

Simple example - HTML template

First: <input type="text" ng-model="person.first" />
Last: <input type="text" ng-model="person.last" />
<button ng:click="save()">Save</button>

JavaScript - 控制器

JavaScript - controller

function FormCntl($scope, $http) {
  $scope.save = function() {
    $http.put('/save.py', $scope.person);
  };
}

这篇关于AngularJS - 如何将表单提交给服务器上的控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆