Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - How do I submit a form to a controller on the server?

The cookbook form examples on the AngularJS site only save the state on the client. How do I submit to the server?

Alternatively, how do I use jQuery's form.submit() on the form in the ng:click="save()" function?

Edit - Found 2 ways to do this ( I also removed the HTML markup I pasted before - just refer to the advanced form cookbook example for the source)

  1. http://webpac2.rot13.org:3000/conference/Work (by Dobrica Pavlinusic) to go the AngularJS way using a resource to send the data to the server in JSON format. I had issues with that on the server side - AngularJS was sending it fine but grails were mangling it (according to firebug and request content-length). I need to look into this more. How do I change the content-type in angular for a resource method like $save()?

  2. Put a form in and use a submit button. Since I am not doing a single page web app, I used this method. Most validations were on the client and a few more on the server which was sufficient for me.

Just putting this here so that someone else can use this for possible solutions and best approach.

like image 423
Rajesh Krishnamoorthy Avatar asked May 21 '11 14:05

Rajesh Krishnamoorthy


People also ask

What is the use of Ngsubmit in angular?

The ng-submit directive specifies a function to run when the form is submitted. If the form does not have an action ng-submit will prevent the form from being submitted.

What is form validation in AngularJS?

Form ValidationAngularJS monitors the state of the form and input fields (input, textarea, select), and lets you notify the user about the current state. AngularJS also holds information about whether they have been touched, or modified, or not.

What is the responsibility of the controller in AngularJS?

The primary responsibility of an AngularJS Controller is to control the data that gets passed to the view. There is two-way communication between the scope and the view .


1 Answers

Note, there is strict separation of view (your html template) and logic (your JS code) - mainly because of testability.

The right way is to just send your model to the server, using $resource (for REST) or low level $http. Instead of doing the job in the template.

Simple example - HTML template

First: <input type="text" ng-model="person.first" />
Last: <input type="text" ng-model="person.last" />
<button ng:click="save()">Save</button>

JavaScript - controller

function FormCntl($scope, $http) {
  $scope.save = function() {
    $http.put('/save.py', $scope.person);
  };
}
like image 121
Vojta Avatar answered Oct 14 '22 19:10

Vojta