4. Step 4 - Implement the Create Use Case

This use case corresponds to the "Create" from the four basic data management use cases Create-Retrieve-Update-Delete (CRUD).

For a data management operation with user input, such as the "create object" operation, an HTML page with an HTML form is required as a user interface. The form typically has an input or select field for each attribute of the model class. In the case of an AngularJS app, we don't have model classes and the UI is defined by a view template partials/createBook.html (an HTML fragment with embedded AngularJS expressions), which has a field for each attribute of the view model object $scope.book. The createBook view template invokes the BooksController method addBook(). In our example app, the request URL path of this page is #/createBook, which renders the following template:

<h1>Public Library: Create a new book record</h1>
<form>
  <div>
    <label>ISBN:
      <input type="text" name="isbn" ng-model="book.isbn" />
    </label>
  </div>
  <div>
    <label>Title:
      <input type="text" name="title" ng-model="book.title" />
    </label>
  </div>
  <div>
    <label>Year:
      <input type="number" name="year" ng-model="book.year" />
    </label>
  </div>
  <div>
    <button type="submit" name="commit" ng-click="addBook()">
      Save
    </button>
  </div>
</form>

Notice how the AngularJS attribute ng-model is used for binding form fields to attributes of the view model $scope.book, resulting in a two-way data binding. Once the submit button is clicked, the function addBook() will be executed. Let's take a look at the BooksController and its function addBook():

plControllers.controller('BooksController',
    ['$scope', '$http', function ( $scope, $http){
  ...
  $scope.addBook = function () {
    $http({
      method: 'POST',
      url: 'https://api.parse.com/1/classes/Book',
      data: {
        isbn: $scope.book.isbn,
        title: $scope.book.title,
        year: $scope.book.year
      }
    })
      .success( function(){
        alert("SUCCESS: Create book");
        $scope.book = {};
      })
      .error( function( data){
        alert("ERROR: Create book", data);
      });
    };
  ...
}]);

Notice that the $http method is invoked with a data parameter holding the attribute-value slots of the object to be saved. When a user enters data in the HTML form fields of the "create book" user interface, the data binding mechanism of AngularJS copies the data to the view model object $scope.book, so when the submit button is clicked, this data is sent to the Parse data store in the form of a HTTP POST request message using Angular's $http method. The Parse cloud storage service receives the message and saves the book data as an instance of the Parse storage class Book.