Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use $http in Angular instead of jquery's ajax?

I don't understand when to use Angular over jquery for ajax requests.

For example, why should I use:

function ItemListCtrl ($scope, $http) {
    $http.get('example.com/items').success(function (data) {
    $scope.items = data;
  }
}

Instead of

  function ItemListCtrl ($scope) {
        $.ajax({type: "GET", url: 'example.com/items',
        success: function (result) {                    
                             $scope.items = data;
                    }
    });
   }

??

like image 609
Shai UI Avatar asked Dec 10 '25 21:12

Shai UI


1 Answers

My understanding is that there are a couple reasons the first is preferred:

  • $http is testable. It's actually possible to stub out the backend that it uses and test $http requests without actually sending requests.
  • $http does some common "stuff" for you, such as setting the content type to 'application/json' for you on POST requests.
  • $http returns a "promise" similar to other areas in angular, which means .success, .done are consistent with angular. jquery also allows for similar, but the syntax is slightly different.
  • $http success and error callbacks will execute inside of angular. If you use jQuery, then it might be necessary to call $apply, which can be tricky in some cases.
  • $http works without jQuery. So if you don't have some other reason to include jQuery, you could possibly save a few k by using $http.
  • $http is shorter. Subjective, but personally, it reads better to me.

Aside from those, though, you generally should be able to do either.

like image 178
Daniel Avatar answered Dec 13 '25 09:12

Daniel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!