Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS. Converting form fields to json

Tags:

json

angularjs

Trying to understand how could be possible to write a function, (directive / controller) that would transform all my form inputs to json with current value that they have to json.

The json would have a format similar to that:

{    
    fields: [
          {field1: value1},
          {field2: value2},
          {field3, value3}
        ]    
}

Where to start from at least.. with no jquery applying?

like image 283
ses Avatar asked Nov 11 '13 21:11

ses


People also ask

How to convert form data to JSON in node JS?

How to Convert Form Data to JSON With Object. fromEntries() Note: For both methods, we can use JSON. stringify() to convert the object into a JSON string, which we can then use to send JSON encoded data to APIs.

How to pass JSON object in FormData?

Using the JSON. stringify() method then format the plain form data as JSON. Specify the HTTP request method as POST and using the header field of the Fetch API specify that you are sending a JSON body request and accepting JSON responses back. Then set the request body as JSON created from the form fields.


1 Answers

ng-model does it for you. A scope variable will be created if you haven't already created it yourself

<form name="myForm" ng-submit="submitMyForm()">
    <input ng-model="fields.name"  />
function myController($scope){
    $scope.submitMyForm=function(){
        /* while compiling form , angular created this object*/
        var data=$scope.fields;  
        /* post to server*/
        $http.post(url, data);        
    }

}

If you have the object to start with in your scope angular will 2 way bind to the input, so any values that are initially set in the scope object will show up in the input

like image 78
charlietfl Avatar answered Sep 23 '22 08:09

charlietfl