LxD Series: Using $http for AJAX

So this is the last post related to AngularJS in LxD Series in today I am covering one of the most basic aspect of SPAs that is, interacting with backend systems. Angular comes with $http object that does something what many of us have been doing with $post/$get/$ajax methods of jQuery. Let’s jump into the code.

So far we were using a predefined array having data of our records. It was something like this:

ngAddressBook.controller('ngAddressListController', ['$scope', function ($scope)
    {
        $scope.contacts = [
            {id:1,first_name:'Jane', last_name:'Doe','Phone':'123-456789','Email':'jane@example.com'},
            {id:2,first_name:'Jhon', last_name:'Doe','Phone':'123-456789','Email':'jhon@example.com'}
        ];
        $scope.getTotalContacts = function () {
            return $scope.contacts.length;
        };
    }]);

Which will now be changed to this:

ngAddressBook.controller('ngAddressListController', function ($scope,$http) {

    $http.get('api.php').success(function(data) {
        $scope.contacts = data;
    });
    $scope.contacts1 = [
        {id:1,first_name:'Jane', last_name:'Doe','Phone':'123-456789','Email':'jane@example.com'},
        {id:2,first_name:'Jhon', last_name:'Doe','Phone':'123-456789','Email':'jhon@example.com'}
    ];
    $scope.getTotalContacts = function () {
        return $scope.contacts.length;
    };
});

$http  object’s get method fetch a page. On successful return it sets data with data return from api.php which returns nothing but a JSON object. Rest is similar what you have already seen.

 

 

That's all folks

 

In coming days I will be covering some new/old exciting technology that I have not done so far. Please let me know via comments or via Email about next thing we should learn together. My email is kadnan AT gmail.

As always, give your feedback via comments or email. Some of you already sent me some suggestions and I thankyou for that.

Final code has been uploaded on Github

Join with me and let’s learn together!

* indicates required