AngularJS using factory method, post data and saving to DB

Angular JS and Codeigniter

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:

<div class="span4 offset1">
<legend>Add a new book</legend>
    <label for="book-name">Book name:</label>
    <input type="text" name="book-name" ng-model="" id="book-name">
    <label for="book-price">Book price:</label>
    <input type="text" name="book-price" ng-model="bookData.price" id="book-price">
    <label for="author-id">Author id:</label>
    <input type="text" name="author-id" ng-model="bookData.authorId" id="author-id">
    <button class="btn btn-large btn-success" ng-click="addNewBook(bookData)">Add</button>

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.

singlePageModule.controller('bookViewCtrl', function($scope,$routeParams,sharedBooks) {
  $ = 'bookViewCtrl';
  sharedBooks.getBooks().then(function(books) {
    $scope.books = books;
  $scope.$on('handleSharedBooks', function(events, books) {
    $scope.books = books;
//  handling the submit button for the form
  $scope.addNewBook = function(bookData) {
    $params = $.param({
      "price": bookData.price,
      "author_id": bookData.authorId

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.

singlePageModule.factory('sharedBooks', ['$http', '$rootScope', function($http, $rootScope) {
  var books = [];
  return {
    getBooks: function() {
      return $http.get(base_url + 'json/get_books_json').then(function(response) {
        books =;
        return books;
    saveBooks: function($params) {
      return $http({
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        url: base_url + 'json/save_book',
        method: "POST",
        data: $params,
        .success(function(addData) {
          books = addData;

Click here to view the file