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/items').success(function (data) {
$scope.items = data;
}
}
Instead of
function ItemListCtrl ($scope) {
$.ajax({type: "GET", url: 'example/items',
success: function (result) {
$scope.items = data;
}
});
}
??
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./items').success(function (data) {
$scope.items = data;
}
}
Instead of
function ItemListCtrl ($scope) {
$.ajax({type: "GET", url: 'example./items',
success: function (result) {
$scope.items = data;
}
});
}
??
Share edited Aug 6, 2018 at 8:14 Adrian 8,6173 gold badges28 silver badges46 bronze badges asked Sep 3, 2013 at 16:03 Shai UIShai UI 52k77 gold badges218 silver badges316 bronze badges 5- You can read stackoverflow./questions/14994391/… it will give you some hints to answer this question yourself ;) – DotDotDot Commented Sep 3, 2013 at 16:05
- Maybe if you're not using jQuery? – Mike Christensen Commented Sep 3, 2013 at 16:05
- 3 I don't get why I'm getting minuses. I'm not manipulating the DOM here. I'm asking why does angular have it's own versions of ajax calls that's all. – Shai UI Commented Sep 3, 2013 at 16:06
- 1 @foreyez Angular has it's own version of ajax calls because angularjs doesn't require jQuery to function, therefore if you weren't using jQuery, you would still be able to easily send cross-browser ajax requests using angularjs's ajax method. – Kevin B Commented Sep 3, 2013 at 16:08
- I see, I guess people are touchy to include both jquery and angular because jquery implies dom manipulations. I just always include jquery in my pages.. – Shai UI Commented Sep 3, 2013 at 16:10
1 Answer
Reset to default 9My 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 mon "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.