Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve all inputs values from a form AngularJS

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

like image 372
Fabrizio Fenoglio Avatar asked Dec 11 '25 11:12

Fabrizio Fenoglio


1 Answers

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(...);
}
like image 110
New Dev Avatar answered Dec 14 '25 00:12

New Dev