文章出處

  $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數據賦值給這個屬性。

 


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()