Tutorial, documenation, or blog post on creating Angular forms and json-based backends

1,130 views
Skip to first unread message

Chris

unread,
Mar 22, 2012, 7:21:11 PM3/22/12
to ang...@googlegroups.com
Has anyone seen a good tutorial on how to create an Angular-based forms that posts data to a python backend for example that can handle it? Angular seems to be expecting something specific in the reply, but I haven't been able to find a clear example. 

What specifically does the server have to return for POSTs and GETs for Angular to be happy with this simple form (content type, object, etc.)? 

<div ng:controller="FormCntl">
  Title: <input type="text" name="book.title" />
  <button ng:click="save()">Save</button>
</div>

function FormCntl($xhr) {
  this.save = function() {
    $xhr('POST', '/book', this.book);
  };
}

Dan Doyon

unread,
Mar 22, 2012, 10:32:33 PM3/22/12
to ang...@googlegroups.com

When dealing with rest services, I think the practice is to send back the url of the newly created object so that it can be shown to return user to update the object that was POSTed. 

 

http://en.wikipedia.org/wiki/Representational_State_Transfer

 

“Create a new entry in the collection. The new entry's URL is assigned automatically and is usually returned by the operation.”

 

So I would say { url: “book/123” }

 

Does this help?

 

--dan

--
You received this message because you are subscribed to the Google Groups "AngularJS" group.
To view this discussion on the web visit https://groups.google.com/d/msg/angular/-/N1QZCbhF19oJ.
To post to this group, send email to ang...@googlegroups.com.
To unsubscribe from this group, send email to angular+u...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/angular?hl=en.


No virus found in this message.
Checked by AVG - www.avg.com
Version: 10.0.1424 / Virus Database: 2113/4886 - Release Date: 03/22/12

Igor Minar

unread,
Mar 23, 2012, 12:37:00 AM3/23/12
to ang...@googlegroups.com
if you use $xhr/$http then you fully control everything. So the backend can return anything.

What is not working for you?

/i

Chris

unread,
Mar 23, 2012, 3:30:49 AM3/23/12
to ang...@googlegroups.com
Hi Dan and Igor, 

Thanks for the quick replies. I'm looking for the best practice Angular Form processing approach to recommend to my students which are using Angualrjs on their projects this term. The learning curve gets harder as they start to handle forms since the documentation is light on the topic. I was hoping that someone already had the example or blog post. 

I apologize in advance for the code dump in the Google group, but I think a very simple example of a controller and backend to support a GET and a form POST for a model would really help beginners to power through the Angularjs learning curve. Here is my rough idea. Simpler approaches and recommendations are appreciated. 

//Angular controller for the form

function FormCntl($resource) {

   this.bookModel = $resource('/book/:id', {id: '@id'});

}

FormCntl.$inject = ['$resource']

FormCntl.prototype = {

   fetch: function(){

     this.id = this.book.id;

     this.book = this.bookModel.get({id: this.id});       

   },

   save: function(){

     this.id = this.book.id;

     this.book = this.bookModel.get({id: this.id}); //This wasn't obvious as I glanced through the docs. What is the best way to pass the form parameters?       

   }    

}


# a simple Google App Engine webservice to support the book model. 

import webapp2 as webapp

from google.appengine.ext.webapp.util import run_wsgi_app

from django.utils import simplejson as json

from google.appengine.ext import db


class Book(db.Model)

 title = db.StringProperty()


class BookHandler(webapp.RequestHandler):

   def get(self, model,id):

       #Fetch the model and return the properties as JSON. Not too hard. 

       book = Book.get_by_id(int(id))

       result = #Build the json doc from the model

       self.response.headers['Content-Type'] = 'application/json'

       self.response.out.write(json.dumps(result))


   def post(self,model,id):

       title = self.request.get('title','default post title')

       book = Book.get_by_id(int(id))

       book.title = title

       book.put()       

       result = #Build the json doc from the model

       self.response.headers['Content-Type'] = 'application/json'

       self.response.out.write(json.dumps(result))

       return


def main():

   application = webapp.WSGIApplication(

       [('/([^/]+)/?([0-9]*)', BookHandler)],

       debug=True)


   run_wsgi_app(application)                    


zdam

unread,
Mar 23, 2012, 6:21:56 AM3/23/12
to ang...@googlegroups.com
Hi,

I wrote a couple of posts about using $resource


This github repo has a full example, but it does use asp.net mvc as the backend.  It may still be useful.  https://github.com/zdam/AngularExample 

Hope it helps,

Cheers, Adam.

Chris

unread,
Mar 25, 2012, 3:13:45 AM3/25/12
to ang...@googlegroups.com
Thanks. I ended up going with something simple like this after some help from the ever helpful Andras S.

<div ng:controller="FormCntl">
Add a book: leave Id blank to create a new book.<br>
Title: <input type="text" name="book.title" />
Id: <input type="text" name="book.id" />
<button ng:click="fetch()">Fetch</button> 
<button ng:click="save()">Save</button><br>
<button ng:click="list()">List</button>
</div>

function FormCntl($resource) {
    this.BookModel = $resource('/book/:id', {id: '@id'}); // this is the resource class
    // create an entity of the resource class, so we will just say `this.book.$save()`
    this.book = new this.BookModel();
    this.books = []
}
FormCntl.$inject = ['$resource']
FormCntl.prototype = {
    fetch: function(){
      this.book = this.BookModel.get({id: this.book.id});       
    },
    save: function(){
      this.book.$save();       
    }
    ,
    list: function(){
      this.books = this.BookModel.query({id: ''});        
    } 
}

Then on the server we only need to support these 4 methods (ignoring delete for now).
GET /book -> returns an array of book objects [{..},{..}]
GET /book/123 -> returns the book object with id=123 {...}
POST /book/123 -> updates the book with id=123 if it exists and returns the updated book object {...}
POST /book  -> if no ID, create a new book from passed parameters and return the book object. {...}

Simpler Angular approaches and ideas are welcome. 

Chris
Reply all
Reply to author
Forward
0 new messages