【问题标题】:Have AngularJS perform logic on form inputs when form submits提交表单时让 AngularJS 对表单输入执行逻辑
【发布时间】:2014-08-26 16:52:34
【问题描述】:

我目前有如下表格:

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

还有一个像这样的控制器:

$scope.first = "first";
$scope.second = "second";

$scope.SUBMIT_URL = DATABASE_URL + "forms/submit/";

$scope.trustSrc = function(src) {
  return $sce.trustAsResourceUrl(src);
};  

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

【问题讨论】:

  • 修复了我的表单以显示我的表单提交。而且我对 HTML 表单不是很熟悉——它似乎是某种xhr,如果我不得不猜测,我会假设它是原生的xhr。网上没有很多资源可以解释&lt;form&gt;在提交时做了什么,所以我没能找到太多。

标签: angularjs forms


【解决方案1】:

目前还不是很清楚你想要完成什么。但是,您应该稍微整理一下代码,以使实现更容易:

  • 不要为每个输入字段使用不同的变量。相反,请使用具有不同键的对象。
  • 使用ng-click(或ng-submit)提交。动作将进入您的 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>

你的 JS 指令是:

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

【讨论】:

    猜你喜欢
    • 2018-02-08
    • 1970-01-01
    • 1970-01-01
    • 2020-11-05
    • 2011-10-12
    • 1970-01-01
    • 2015-02-19
    • 1970-01-01
    • 2016-02-19
    相关资源
    最近更新 更多