angularjs與server互動

來源:互聯網
上載者:User

標籤:targe   ble   com   ott   angularjs   查詢   jsonp   而不是   ng-repeat   

真正的應用須要和真實的server進行互動,行動裝置 App和新興的Chrome案頭應用可能是個例外,可是對於此外的全部應用來說,不管你是想把資料持久化到雲端。還是須要與其它使用者進行即時互動。都須要讓應用與server進行互動。

為了實現這一點。Angular提供了一個叫做$http的服務。它提供了一個可擴充的抽象方法列表。使得與server的互動更加easy。

它支援HTTP、JSONP和CORS方式。它還包括了安全性支援。避免JSON格式的脆弱性和XSRF。它讓你能夠輕鬆地轉換請求和響應資料,甚至還實現了簡單的緩衝。

例如,我們打算讓購物網站從server上擷取商品資訊,而不是從記憶體假資料擷取。怎樣編寫服務端代碼已經超越了本書的範疇。所以,我們只來想象一下,例如說我們已經建立了一個server,當查詢/products 路徑時。它會以JSON格式返回一個商品列表。

返回的響應示比例如以下:
[
  {
    "id": 0,
    "title": "Paint pots",
    "description": "Pots full of paint",
    "price": 3.95
  },
  {
    "id": 1,
    "title": "Polka dots",
    "description": "Dots with that polka groove",
    "price": 12.95
  },
  {
    "id": 2,
    "title": "Pebbles",
    "description": "Just little rocks, really",
    "price": 6.95
  }
  ...etc...
]

我們能夠像以下這樣編寫查詢代碼:
function ShoppingController($scope, $http) {
  $http.get(‘/products‘).success(function(data, status, headers, config) {
    $scope.items = data;
  });
}

然後在模板中這樣使用它:
<body ng-controller="ShoppingController">
    <h1>Shop!</h1>
    <table>
      <tr ng-repeat="item in items">
        <td>{{item.title}}</td>
        <td>{{item.description}}</td>
        <td>{{item.price | currency}}</td>
      </tr>
    </table>
  </div>
</body>

正如我們前面講過的,從長遠來看,讓服務來代理與server互動的工作對我們有優點,這個服務能夠被多個控制器共用。

來自《AngularJS開發下一代Web應用》一書 

線上版在https://github.com/edagarli/AngularJSWeb

angularjs與server互動

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.