Built.io Blog

Introduction to AngularJS Part 2

,

In part one, we saw a basic example of how AngularJS works. In this part we are going to enhance that application, and modify it to run against a REST server. You can find the code for this tutorial and Part 1 on Github.

First you will have to modify the declaration of your controller to:

function StudentController($scope, $http){
  var loadStudents = function(){
    $scope.students = [];
    $http.get('/students.json')
      .success(function(response, status, headers, config){
        $scope.students = response.students;
      })
      .error(function(response, status, headers, config){
        $scope.error_message = response.error_message;
      });
  }
  loadStudents();
}

The $http service is a core Angular service that facilitates communication with the remote HTTP servers via browser's XMLHttpRequest object or via JSONP (Source: AngularJS API). You can use the four basic HTTP verbs (GET, POST, PUT, DELETE) with this service, which proves to be more than sufficient. In the above code, we have used the GET function and provided the resource url to it. Then we used chained functions as callbacks for success, as well as error. You can also implement the API calls as:

$http({method: 'GET', url: "/someUrl"})
  .success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
  })
  .error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

The callback functions give you four variables:

  1. data => Response Body
  2. status => HTTP status
  3. headers => Response Headers
  4. config => The config json provided by you for sending request.

We listed the students we received from the API server. To create one, you will have to modify the $scope.createStudent function in the StudentController as below:

$scope.newStudent = function(){
  $scope.enterNew = true;
  $scope.student = {};
};
$scope.createStudent = function(){
  $http.post('/students.json', {"student": $scope.student})
    .success(function(response, status, headers, config){
      $scope.students.push(response.student);
      $scope.enterNew = false;
    })
   .error(function(response, status, headers, config){
     $scope.error_message = response.error_message;
   });
}

This will send a post request to the API server with the student data entered in the new student form as body parameters. If the API call is processed without errors, then the success callback will be called, and the student data in the response body will be added to the students array in the current scope.

To edit a student data, and modify our updateStudent function accordingly:

$scope.editStudent = function(student){
  $scope.enterNew = false;
  $scope.editing = true;
  $scope.student = student;
};
$scope.updateStudent = function(){
  $http.put('/students/' + $scope.student.id + '.json', {"student": $scope.student})
  .success(function(response, status, headers, config){
    $scope.student = response.student;
    $scope.enterNew = false;
    $scope.editing = false;
  })
  .error(function(response, status, headers, config){
    $scope.error_message = response.error_message;
  });
};

And finally, modify the delete functionality as well:

$scope.deleteStudent = function(student){
$http.delete('/students/' + student.id + '.json')
  .success(function(response, status, headers, config){
    var index = $scope.students.indexOf(student);
    $scope.students.splice(index,1);
  })
  .error(function(response, status, headers, config){
    $scope.error_message = response.error_message;
  });
}

That's it; we have modified our codebase in the first part which was a static AngularJS application, to a REST-based AngularJS application. And the fun part was, we didn't even touch our HTML file, just some modifications in our controller and voilà!

In the next post we will see how we can create our own custom services in AngularJS.

You can find all this code and future updates on GitHub.

Subscribe to our blog