$http 是 AngularJS 中的一个核心服务,用于读取远程服务器的数据。
读取 JSON 文件
下是存储在web服务器上的 JSON 文件:
{ "records": [ { "Name": "Alfreds Futterkiste", "City": "Berlin", "Country": "Germany" }, { "Name": "Ana Trujillo Emparedados y helados", "City": "Mxico D.F.", "Country": "Mexico" }, { "Name": "Antonio Moreno Taquera", "City": "Mxico D.F.", "Country": "Mexico" }, { "Name": "Around the Horn", "City": "London", "Country": "UK" }, { "Name": "B's Beverages", "City": "London", "Country": "UK" }, { "Name": "Berglunds snabbk枚p", "City": "Lule", "Country": "Sweden" }, { "Name": "Blauer See Delikatessen", "City": "Mannheim", "Country": "Germany" }, { "Name": "Blondel pre et fils", "City": "Strasbourg", "Country": "France" }, { "Name": "Blido Comidas preparadas", "City": "Madrid", "Country": "Spain" }, { "Name": "Bon app'", "City": "Marseille", "Country": "France" }, { "Name": "Bottom-Dollar Marketse", "City": "Tsawassen", "Country": "Canada" }, { "Name": "Cactus Comidas para llevar", "City": "Buenos Aires", "Country": "Argentina" }, { "Name": "Centro comercial Moctezuma", "City": "Mxico D.F.", "Country": "Mexico" }, { "Name": "Chop-suey Chinese", "City": "Bern", "Country": "Switzerland" }, { "Name": "Comrcio Mineiro", "City": "So Paulo", "Country": "Brazil" } ]}
AngularJS $http
AngularJS $http 是一个用于读取web服务器上数据的服务。
$http.get(url) 是用于读取服务器数据的函数。
- { { x.Name + ', ' + x.Country }}
结果:
- Alfreds Futterkiste, Germany
- Ana Trujillo Emparedados y helados, Mexico
- Antonio Moreno Taquera, Mexico
- Around the Horn, UK
- B's Beverages, UK
- Berglunds snabbk枚p, Sweden
- Blauer See Delikatessen, Germany
- Blondel pre et fils, France
- Blido Comidas preparadas, Spain
- Bon app', France
- Bottom-Dollar Marketse, Canada
- Cactus Comidas para llevar, Argentina
- Centro comercial Moctezuma, Mexico
- Chop-suey Chinese, Switzerland
- Comrcio Mineiro, Brazil
应用解析:
AngularJS 应用通过 ng-app 定义。应用在 <div> 中执行。
ng-controller 指令设置了 controller 对象 名。
函数 customersController 是一个标准的 JavaScript 对象构造器。
控制器对象有一个属性: $scope.names。
$http.get() 从web服务器上读取静态 JSON 数据。
服务器数据文件为: 我这儿是写了text.json。
当从服务端载入 JSON 数据时,$scope.names 变为一个数组。
注:以上代码也可以用于读取数据库数据。
转载地址:http://www.runoob.com/angularjs/angularjs-http.html