Skip to content

Commit

Permalink
finish ch2 'talk to servers'
Browse files Browse the repository at this point in the history
  • Loading branch information
aztack committed May 8, 2013
1 parent e0cec56 commit f53defa
Showing 1 changed file with 62 additions and 0 deletions.
Expand Up @@ -1267,3 +1267,65 @@ __controllers.js__
与服务器通讯
-----------
好了,已经拖了很久了。真实应用多是要和服务器通讯的。移动应用和新近出现的Chrome桌面应用可能是特例,但是对于剩下的,不管你希望数据持久化在云端或者和其他用户实时交互,你的应用基本上需要和服务器通讯。
Angular为此提供了*$http*服务。它有很多用于简化与服务器通讯的抽象接口。它支持普通的HTTP,[JSONP](http://en.wikipedia.org/wiki/JSONP)和[CORS](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing)。还包括防止JSON漏洞攻击和伪造跨站请求([XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery))攻击的安全措施。它允许你轻松的转换请求和响应数据,它甚至还实现了简单的缓存功能。
假设,我们想从我们的购物车网站的服务器获取商品信息,而不使用模拟数据。服务端如何编写我们就不讲了,所以,假设我们已经有了这么一个后端服务*/products*,返回商品列表的JSON数据:
返回数据例如:
```javascript
[
{
"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...
]
```
请求数据的代码:
```javascript
function ShoppingController($scope, $http){
$http.get('/products').success(function(data, status, headers, config){
$scope.items = data;
})
}
```
在模板中这样使用:
```html
<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>
</body>
```
就像我们之前讲过的一样,将与服务器交互的代码放到一个服务中可以实现在多个控制器中共享代码,长远来讲会给我们带来很多好处。我们将会在第五章全面讲解*$http*。
使用#{Directive}更新DOM
-----------------------

0 comments on commit f53defa

Please sign in to comment.