Retrieve all inputs values from a form AngularJS

2020-04-11 18:32发布

I have a massive form with more or less 80 / 90 inputs.

My main problem is How can I pass all those inputs belonging to unique form in an ajax request without map the inputs manually into a object?

I know that with jquery you can use serialize() function selecting the form. Is there any helper function in angular to achieve that?

Thanks

1条回答
We Are One
2楼-- · 2020-04-11 18:50

Indeed, as Michal's comment suggested, it doesn't look like you are using ng-model.

Angular's jqLite doesn't support serialize() since with Angular one would typically build a ViewModel that would then be bound to a form.

But, if you are out of luck, you could add jQuery.js to get the serialize() support and create a simple directive - serializer - that would act on a form.

app.directive("serializer", function(){
  return {
    restrict: "A",
    scope: {
      onSubmit: "&serializer"
    },
    link: function(scope, element){
      // assuming for brevity that directive is defined on <form>

      var form = element;

      form.submit(function(event){
        event.preventDefault();
        var serializedData = form.serialize();

        scope.onSubmit({data: serializedData});
      });

    }
  };
});

And use it as follows:

<form serializer="submit(data)">
  <input name="foo">
  <input name="bar">
  <button type="submit">save</button>
</form>

And in the controller:

$scope.submit = function(data){
   console.log(data);
}

plunker

EDIT:

If you are using ng-model and in fact have a proper ViewModel, then this is the "Angular way" and so, you should have some object that is bound to the form inputs - you should just submit that.

<form name="foo" ng-submit="onSubmit()">
  <input ng-model="fooObject.a">
  <input ng-model="fooObject.b">
  ...
</form>

$scope.fooObject = {};
$scope.onSubmit = function(){
   $http.post("url/to/server", {data: $scope.fooObject})
     .success(...);
}
查看更多
登录 后发表回答