$http Service
Promise-based HTTP requests with config object and error handling.
Code
angular.module('httpApp', [])
.controller('HttpController', function($scope, $http) {
$scope.users = [];
$scope.loading = false;
$scope.error = null;
$scope.loadUsers = function() {
$scope.loading = true;
$http.get('/api/users')
.then(function(response) {
$scope.users = response.data;
})
.catch(function(error) {
$scope.error = 'Failed to load: ' + error.status;
})
.finally(function() {
$scope.loading = false;
});
};
$scope.addUser = function(user) {
$http.post('/api/users', user)
.then(function(res) { $scope.users.push(res.data); });
};
// Config object form with params and headers
$http({
method: 'GET',
url: '/api/users',
params: { page: 1, limit: 20 },
headers: { 'Authorization': 'Bearer token' }
});
});Explanation
$http returns a promise resolving to a response object with data, status, headers, and config. Convenience methods (get, post, put, delete) cover common verbs, while the config-object form exposes params, headers, and body. AngularJS auto-applies digest-cycle updates after promise resolution, so scope changes render automatically.
More AngularJS Snippets
Module & Controller
Define a module and a controller with scope methods.
Scope Inheritance
Prototypal scope inheritance between parent and child controllers.
Custom Directives
Attribute directive and element directive with isolated scope.
Services & Factories
Factory and service singletons for shared state and logic.
Routing (ngRoute)
Configure routes with templates, controllers, and resolve guards.
Custom Filters
Chainable filters for formatting values in templates.