有没有更好的方法来收集角形式数据(提交)

时间:2015-04-02 02:17:26

标签: angularjs

这是我的解决方案,但我不知道这是否正确。

HTML:

<div ng-controller='myctrl as mc'>
  <form name='mc.form' ng-submit='mc.submit'>
    <input type='email' name='email' />
    <input type='user' name='user' />
    <button type='submit'>submit</button>
  </form>
</div>

的javascript:

angular.module('myapp').controller('myctrl', ['$scope', function myctrl($scope) {

    var th = this

    this.submit = function(form) {
        if(!th.form.$invalid) postToServer(getFormData())
    }

    //I checked the form object, no helper method like this
    function getFormData() {
        var res = {}
        angular.forEach(th.form, function(value, key) {
            if(key[0] !== '$') res[key] = value.$modelValue
        })
        return res
    }

    function postToServer(data) {
        //do post to server
        console.log(data)
    }


}])

2 个答案:

答案 0 :(得分:2)

这是Angular Forms基本用法的一个示例。您想使用ng-modal,并且在Controller $scope内,您应该有一个对象来处理您要处理的表单数据。如果您为表单指定了name属性,则会将其绑定到Controller $scope,以便您可以在控制器中访问,例如<form name="myForm"> == $scope.myForm

请在下方找到此实例,如果您打开Console F12菜单,则会在提交时看到表单数据。

http://plnkr.co/edit/XSiPnDdB5umxOzu0V3Pf?p=preview

<form name="myForm" ng-submit="submitForm()">
    Email: <input name="email" type="email" ng-model="formData.email" />
    <br />
    User: <input name="user" type="text" ng-model="formData.user" />
    <br />
    <button type="submit">Submit</button>
</form>
<script>
    angular.module('myApp', [])
        .controller('mainCtrl', function($scope) {
            $scope.formData = {};

            $scope.submitForm = function() {
                // do form submit logic

                // this is the object declared in the controller
                // binded with ng-model
                console.log('$scope.formData');
                console.log($scope.formData);

                // this is the ng-form $scope binded into
                // the Controller via <form name="name">
                // this hold more that just the form data
                // validation errors form example
                console.log('$scope.myForm');
                console.log($scope.myForm);
            };
        });
</script>

答案 1 :(得分:1)

您应该使用ng-model,它将所有表单数据作为对象发送

<div ng-controller='myctrl as mc'>
   <form name='mc.form' ng-submit='mc.submit'>
       <input ng-model='formData.email' name='email' />
       <input ng-model='formData.user' name='user' />
       <button type='submit'>submit</button>
   </form>
</div>

输入值将绑定到控制器

中对象调用formData的属性
angular.module('myapp').controller('myctrl', ['$scope',
  function myctrl($scope) {

    var th = this;
    $scope.formData= {}; //Initialise the object

    this.submit = function(form) {
      if (!th.form.$invalid) postToServer();
    }

    function postToServer() {
      //do post to server
      console.log($scope.formData); //The value of input will bind to the property of formData
    }

  }
])