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
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.
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.
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.