Amitav Roy

Blog on web and travel

AngularJS using factory method, post data and saving to DB

Posted on 19 Mar 2013 by Amitav Roy

AngularJS using factory method, post data and saving to DB

In the last tutorial, I showed how we can use the factory method to share an object (in our case the list of books) and then we displayed those books in our view. The next step is to post data so that we can add another book to the database and that will also update the main listing. So, in this tutorial I will show you how to do that.

Setting up the form

In the first step, I have built the Add book form right next to the listing of the books. Let me remind you I have not opened a form tag and posting a data. Everything here will be done through javascript. The “Add” button calls the addNewBook() function passing the bookData. Here is the code for the controller:

Setting up the controller with the submit function

Now that the form is complete, let’s handle the submit function for the button click which we have mentioned in ng-click. We will be writing the function inside the “bookViewCtrl” controller as the form is still inside the same controller. We had passed the bookData on click and inside the function first we create the $params which will use the bookData object. This $param is then passed to the sharedBooks.saveBooks function which will do the main work of posting the data to the desired url. We will look at the sharedBooks.saveBooks after we setup the post controller.

Click here to view the file

Setting up the controller

Next, although we won’t post the form, we do need a page where we would submit the ajax post. So, we use the json controller. Inside this controller, I have added another function “save_book”. This will take the post data and do an insert to the database. Once done, I will return the list of books available.

[NOTE: Here I am fetching all the records again from the DB after the post instead of appending the latest record because my number of records are small. But in actual production environment get the latest inserted item and then add that to the existing javascript object]

Click here to view the file

Setting up the factory method

Inside the sharedBooks.saveBooks method we passed the params which we have set up in the controller. Now, we will use the http service again, setting a header “Content-Type” which is very important, the post url, method and the data – which is very similar to the jQuery ajax function.

On the success of this function we have populated the books object with the latest set of books (here we can fetch the last record inserted and append to the object instead of fetching all of the entries as mentioned earlier in the note). And also I am calling the broadcast so that all the instance which is using the sharedBooks object gets the updated object.