14

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?

1 Answer 1

46

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

Sign up to request clarification or add additional context in comments.

7 Comments

var query = [ StartDate= $scope.StartDate.toPlanoLocalDateString(), EndDate= $scope.EndDate.toPlanoLocalDateString() ]; var tstring = jQuery.parseJSON(query); sir...i need to transfer these values to controller.How can i use this ...
@Sankar sould start with valid javascript.
@amit_yo same way you do any other ajax
This works fine, I have a php backend and using $_POST, how do I read the fields.name value?
@defmx default content type of $http is application/json so $_POST is empty. Need to use json_decode(file_get_contents('php://input'));
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.