Angular学习(十五)——Route和$location/与服务器交互
来源:互联网 发布:中国核弹数量知乎 编辑:程序博客网 时间:2024/06/02 20:51
通过Route和$location改变视图
尽管Ajax应用在技术上算是单页面应用(因为他们在第一请求加载时,加载HTML页面,燃火就是用DOM更新那些作用域),但是我们通常有多个子页面视图,适当的时候想用户展现或隐藏。
我们可以使用$route服务来为我们管理这种场景。route可以为一个给定的浏览指向URL详细制定Angular能够加载和显示的一个模板,实例化一个控制器为模板提供上下文。
在应用中可以在$routeProvider服务上调用函数创建路由作为一个配置块。有点象下面的伪代码:
var someModule = angular.module('someModule',[...module dependencies...])
someModule.config(function($routeProvider){
$routeProvider.
when('url',{controller:aController,templateUrl:'/path/to/template'}).
when(...other mapping for your app ...).
...
otherwise(... what to do if nothing else matches ...);
});
上面代码的意思是:当浏览器的URL变成制定的URL时,Angular将加载/path/to/templete下的模板,同时用aController管理这个模板的根元素(假设我们输入了一个aController控制器)。
最后一行的otherwise()告诉路由如果没有匹配到相应的路径时就默认执行这一步。
与服务器交互
在Angular中,它提供了一个叫$http的服务来为应用和服务器进行交互。$http有一些列的抽象扩展,使和服务交互变得很容易,它能够支持HTTP、JSONP、CORS,包括安全措施防止JSON泄露和XSRF攻击。它能够让你传输请求与响应数据更简单,甚至可以实现简单的缓存。
比方说,我们想从服务端的购物站点检索商品,而不是从模拟的内存中获取。假设我们已创建了一个服务,当调用/products服务时会返回一个JSON的产品列表,这里给出了一个示例如下:
[{"id":0,"title":"Paint pots","description":"Pots full of paint","price":3.95},
{"id":1,"title":"Paint pots","description":"Pots full of paint","price":3.95},
{"id":2,"title":"Paint pots","description":"Pots full of paint","price":3.95},
......]
我们可以写一个类似这样的查询服务:
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></body>
正如之前所学习的那样,从长远来看,把与服务器端交互的工作委派给一各可以跨控制器共享的服务是一种很不错的选择。
- Angular学习(十五)——Route和$location/与服务器交互
- angular学习(十五)——Provider
- Angular学习-$location
- Angular学习-ng-route与ui-router路由的区别
- 【Angular】——Angular Route路由传参
- Android学习总结(2)——App客户端与服务器交互中的token
- angular route
- Angular-route
- AngularJS进阶(二十五)requirejs + angular + angular-route 浅谈HTML5单页面架构
- angular.js学习(1)--指令和控制器间的交互
- 关于base href和angular-route
- Angular学习(九)——Hidding和Showing
- requirejs + angular + angular-route
- 前端学习总结(七)Angular.js——以数据交互为核心的前端框架
- ANGULAR学习笔记(三十一)-$LOCATION(1)
- [转]angular学习笔记(三十一)-$location(1)
- Angular location
- Http与服务器的交互(主要post和get)
- 黑马程序员_异常
- LeetCode - Array - Maximum Subarray
- java-泛型学习
- PLsql
- WIN7 下 Qt Creator 安装 QWT (转)
- Angular学习(十五)——Route和$location/与服务器交互
- 【九度OJ】1047【素数判断】
- 【缩点】HDU 2767 Proving Equivalences
- 在VC中使用CCheckListBox
- C++的继承操作---基类指针访问派生类问题---基类成员恢复访问属性问题
- C/C++ 回调函数详解
- commons-fileupload+servlet实现简单文件上传
- LeetCode Climbing Stairs
- Windows 8.1 读取OAKEY代码