您的位置:首页 > 理论基础 > 计算机网络

AngularJS快速入门指南07:Http对象

2015-05-11 14:02 621 查看
  $http是AngularJS提供的一个服务,用来从远程服务器读取数据。

提供数据

  下面的数据由Web服务器提供:

{
"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

  AngularJS $http是一个从Web服务器读取数据的核心服务。

  $http.get(url)是一个用来从服务器读取数据的函数。

<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>元素内运行。

  ng-controller指令定义了控制器的名称。

  customersCtrl函数是一个标准的JavaScript对象构造函数。

  AngularJS通过$scope$http对象调用customersCtrl函数。

  $scope是一个appliation object(即application的变量及函数的所有者)。

  $http是一个用来请求外部数据的XMLHttpRequest object

  $http.get()函数从服务器读取JSON数据

  如果成功的话,控制器将在$scope对象中创建一个names属性,并将从服务器端返回的JSON数据赋值给这个属性。

上一章 - AngularJS快速入门指南06:过滤器
下一章 - AngularJS快速入门指南08:表格
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: