$http是AngularJS提供的一個服務,用來從遠程服務器讀取數據。php
下面的數據由Web服務器提供:html
{ "records": [ { "Name" : "Alfreds Futterkiste", "City" : "Berlin", "Country" : "Germany" }, { "Name" : "Berglunds snabbköp", "City" : "Luleå", "Country" : "Sweden" }, { "Name" : "Centro comercial Moctezuma", "City" : "México D.F.", "Country" : "Mexico" }, { "Name" : "Ernst Handel", "City" : "Graz", "Country" : "Austria" }, { "Name" : "FISSA Fabrica Inter. Salchichas S.A.", "City" : "Madrid", "Country" : "Spain" }, { "Name" : "Galería del gastrónomo", "City" : "Barcelona", "Country" : "Spain" }, { "Name" : "Island Trading", "City" : "Cowes", "Country" : "UK" }, { "Name" : "Königlich Essen", "City" : "Brandenburg", "Country" : "Germany" }, { "Name" : "Laughing Bacchus Wine Cellars", "City" : "Vancouver", "Country" : "Canada" }, { "Name" : "Magazzini Alimentari Riuniti", "City" : "Bergamo", "Country" : "Italy" }, { "Name" : "North/South", "City" : "London", "Country" : "UK" }, { "Name" : "Paris spécialités", "City" : "Paris", "Country" : "France" }, { "Name" : "Rattlesnake Canyon Grocery", "City" : "Albuquerque", "Country" : "USA" }, { "Name" : "Simons bistro", "City" : "København", "Country" : "Denmark" }, { "Name" : "The Big Cheese", "City" : "Portland", "Country" : "USA" }, { "Name" : "Vaffeljernet", "City" : "Århus", "Country" : "Denmark" }, { "Name" : "Wolski Zajazd", "City" : "Warszawa", "Country" : "Poland" } ] }
AngularJS $http是一個從Web服務器讀取數據的核心服務。服務器
$http.get(url)是一個用來從服務器讀取數據的函數。app
<div ng-app="myApp" ng-controller="customersCtrl"> <ul> <li ng-repeat="x in names"> {{ x.Name + ', ' + x.Country }} </li> </ul> </div> <script> var app = angular.module('myApp', []); app.controller('customersCtrl', function($scope, $http) { $http.get("http://example.php") .success(function(response) {$scope.names = response.records;}); }); </script>
代碼解釋:函數
AngularJS application經過ng-app指令定義。application在<div>元素內運行。ui
ng-controller指令定義了控制器的名稱。url
customersCtrl函數是一個標準的JavaScript對象構造函數。spa
AngularJS經過$scope和$http對象調用customersCtrl函數。code
$scope是一個appliation object(即application的變量及函數的全部者)。htm
$http是一個用來請求外部數據的XMLHttpRequest object。
$http.get()函數從服務器讀取JSON數據。
若是成功的話,控制器將在$scope對象中建立一個names屬性,並將從服務器端返回的JSON數據賦值給這個屬性。