Updated on Kisan Patel
The $http
service handles AJAX requests via the browser’s XMLHttpRequest object or via JSONP.
The $http
service is a function that takes a single argument: a configuration object that is used to generate a HTTP request. The function returns a promise that has two helper methods: success and error.
$http({ method: 'GET', url: '/api/users.json' }).success(function(data, status, headers, config) { // This is called when the response is // ready }).error(function(data, status, headers, config) { // This is called when the response // comes back with an error status });
Lets implement a controller using the $http
service to fetch the data and store it in the scope.
<div ng-app="app" ng-controller="studentController"> <table border="1"> <tr ng-repeat="student in students"> <td>{{ student.Id}}</td> <td>{{ student.Name}}</td> <td>{{ student.RollNo}}</td> </tr> </table> </div>
<script type="text/javascript"> var myModule = angular.module("app", []); myModule.controller('studentController', function ($scope, $http) { $scope.students = []; $http({ method: "GET", url: "/api/student" }) .success(function (data, status, headers, config) { angular.copy(data, $scope.students); }).error(function (data, status, headers, config) { }); }); </script>
[ {"Id":1,"Name":"Ravi","RollNo":23}, {"Id":2,"Name":"Kisan","RollNo":32}, {"Id":3,"Name":"Devang","RollNo":45} ]
The output will be:
The $http
service supports the HTTP verbs get, head, post, put, delete and jsonp. The following code shows simple POST request example (passing data):
$http({ method: "POST", url: "/api/student", data: { Name: 'Kiran', RollNo: '76'} }) .success(function (data, status, headers, config) { console.log(data); angular.copy(data, $scope.students); }).error(function (data, status, headers, config) { });