表单提交时,让AngularJS对表单输入执行逻辑

表单提交时,让AngularJS对表单输入执行逻辑,angularjs,forms,Angularjs,Forms,我目前有一个类似以下的表格: <form autocomplete="on" enctype="multipart/form-data" accept-charset="UTF-8" method="POST" action="{{trustSrc(SUBMIT_URL)}}"> <input type="text" name="firstinput" ng-model="first"/> <input type="text" name="secondinp

我目前有一个类似以下的表格:

<form autocomplete="on" enctype="multipart/form-data" accept-charset="UTF-8" method="POST" action="{{trustSrc(SUBMIT_URL)}}">
  <input type="text" name="firstinput" ng-model="first"/>
  <input type="text" name="secondinput" ng-model="second"/>
  <input type='submit'/>
</form>

当我按原样提交此表单时,它与后端配合得很好。但是,我现在需要使用
ng submit
来代替标准的HTML表单submit,因为我需要在
$scope.first
中运行查找和替换。后端希望数据完全按照原始HTML表单的方式发布。如何使用
$http
$resource
以与HTML表单完全相同的格式发布内容?

不太清楚您想要实现什么。但是,您应该稍微整理一下代码,以使实现更容易:

  • 不要对每个输入字段使用不同的变量。相反,请使用具有不同关键点的对象
  • 使用
    ng单击
    (或
    ng提交
    )进行提交。操作将进入JS逻辑
  • 使用
    novalidate
    属性,以便Angular可以正确设置格式,并自行验证表单(并且不会产生令人困惑的跨浏览器效果)
记住这些,您的新标记将是:

<form autocomplete="on" enctype="multipart/form-data" accept-charset="UTF-8" novalidate>
    <input type="text" name="first" ng-model="form.first" />
    <input type="text" name="second" ng-model="form.second" />
    <button ng-click="submit">Submit</button>
</form>

修正了我的表单以显示我的表单提交。我对HTML表单不是很熟悉——它似乎有点像
xhr
,如果我不得不猜测的话,我会假设它是原生的
xhr
。网上没有太多的资源来解释
在提交时所做的事情,所以我无法找到太多。
<form autocomplete="on" enctype="multipart/form-data" accept-charset="UTF-8" novalidate>
    <input type="text" name="first" ng-model="form.first" />
    <input type="text" name="second" ng-model="form.second" />
    <button ng-click="submit">Submit</button>
</form>
app.directive('form', function($http)
{
    return function(scope, element, attrs)
    {
        // Leave this empty if you don't have an initial data set
        scope.form = {
            first  : 'First Thing To Write',
            second : 'Second item'
        }

        // Now submission is called
        scope.submit = function()
        {
            // You have access to the variable scope.form
            // This contains ALL of your form and is in the right format
            // to be sent to an backend API call; it will be a JSON format

            // Use $http or $resource to make your request now:
            $http.post('/api/call', scope.form)
                 .success(function(response)
                 {
                    // Submission successful. Post-process the response
                 })
        }
    }
});