之前有写过一篇关于angular自带的路由:ngroute。今天来说说angular的第三方路由:ui-router。那么有人就会问:为什么angular有了自带的路由,我们还需要用ui-router呢?这里简单明了的说明下ngroute和ui-router的区别吧,其实也没很大的区别,主要的就是ngroute针对于单视图,而ui-router可用于多视图(这里说的视图是指在页面内我们可控制的,可变化的区域)。
比如我们点击了一个link,我们需要在视图中跳转到指定的一个页面,那么ngroute已经满足了我们的需求,而当我们点击的时候,需要在分别在不同的地方跳转两个不同的页面的时候,ngroute就不够用了,我们就需要用到ui-router。
这里我们还是先来学习下ui-router(一些简单的服务和用法)
ui-router
$urlrouterprovider
$urlrouterprovider负责监听$location.当$location变化的时候,$urlrouterprovider开始在一个规则的列表中一个个的查找,直到找到匹配的值。$urlrouterprovider用于在后端指定url的状态配置。所有的url被编译成urlmatcher对象。
依赖: $urlmatcherfactoryprovider $locationprovider
方法:
deferintercept(defer);
禁用(或启用)延迟location变化的拦截。如果你想定制与url同步的行为(例如,你需要保持当前的url去并且推迟一个变化),那么在配置的时候使用这个方法。
参数:
defer:boolean,确定是禁止还是启用该拦截。
代码:
angular.module('demo',['ui.router']) .config(["$urlrouterprovider",function(){ $urlrouterprovider.deferintercept(defer); // defer = true/false }])
这是源码部分:
this.deferintercept = function (defer) { if (defer === undefined) defer = true; interceptdeferred = defer; // 默认是true };
otherwise(rule);
定义一个当请求的路径是无效路径时跳转的路径。
rule:你想重定向的url路径或一个返回的网址路径的规则函数。函数传入两个参数:$injector和$location服务,而且必须返回一个string的url。
代码:
angular.module('demo',['ui.router']) .config(["$urlrouterprovider",function(){ $urlrouterprovider.otherwise(rule); // rule = 重定向的url规则 }])
rule(rule);
定义使用$urlrouterprovider 来匹配指定的url的规则。
参数:
rule:将$injector和$location作为arguments传入的处理函数。用来返回一个string类型的url路径。
代码:
angular.module('demo',['ui.router']) .config(["$urlrouterprovider",function($urlrouterprovider){ $urlrouterprovider.rule(function ($injector, $location) { var path = $location.path(), normalized = path.tolowercase(); if (path !== normalized) { return normalized; } }); }])
when(what,handler);
为给定的url匹配注册一个处理程序。
参数:
what:需要重定向的传入路径。
handler:你想要重定向的路径/处理程序。
代码:
angular.module('demo', ['ui.router']); .config(["$urlrouterprovider",function ($urlrouterprovider) { $urlrouterprovider.when($state.url, function ($match, $stateparams) { if ($state.$current.navigable !== state || !equalforkeys($match, $stateparams) { $state.transitionto(state, $match, false); } }); }]);
$urlrouter
依赖:$location $rootscope $injector $browser
方法:
href(urlmacther,params,options);
一个生成url的方法,为给定的urlmatcher返回编译后的url,并且用提供的参数填充。
参数:
代码:
$bob = $urlrouter.href(new urlmatcher("/about/:person"), { person: "bob" }); // $bob == "/about/bob"; sync();
sync();
触发更新:发生在地址栏url变化时执行相同的更新。
$state
$state服务负责代表状态及提供状态之间的转换。它还提供你当前的状态及上一个状态。
依赖:$rootscope $q $view $injector $resolve $stateparams $urlrouter
方法:
get(stateorname,context);
返回任何指定的状态或所有状态的配置对象。
参数:
方法:
go(to,params,options);
参数:
代码:
$state.go('contact.detail');
href(stateoename,params,options);
一个url生成方法,返回为给定的状态填充指定的参数编译后的链接。
参数:
代码:
$state.href("about.person", { person: "bob" })
include(stateorname,params,options);
一个确定当前有效的状态是不是与stateorname平级的还是其子状态。
参数:
代码:
<div ng-class="{highlighted:$state.includes('.item')}">item</div>
$state.$current.name = 'contacts.details.item'; $state.includes("contacts"); // true $state.includes("contacts.details"); // true $state.includes("contacts.details.item"); // true $state.includes("contacts.list"); // false $state.includes("about"); // false
全局模式:
$state.$current.name = 'contacts.details.item.url'; $state.includes("*.details.*.*"); // true $state.includes("*.details.**"); // true $state.includes("**.item.**"); // true $state.includes("*.details.item.url"); // true $state.includes("*.details.*.url"); // true $state.includes("*.details.*"); // false $state.includes("item.**"); // false
is(stateorname,params,options);
与$state.include相似,只是这个针对的是全名。参数性质同上。
代码:
<div ng-class="{highlighted: $state.is('.item')}">item</div>
$state.$current.name = 'contacts.details.item'; $state.is('contact.details.item'); // true $state.is(contactdetailitemstateobject); // true
reload(state);
重新载入当前状态的方法。
参数:
state:一个状态名称或者状态对象。
代码:
$state.reload('contact.detail');
transitionto(to,toparams,options);
过渡到一个新状态的方法。
参数:
代码:
$state.transitionto($state.current, $stateparams, { reload: true, inherit: false, notify: true });
事件:
1 、$statechangeerror
路由状态变化发生错误时触发的事件。参数有:event,tostate,toparams,fromstate,fromparams,error。以上根据字面意思即可理解,哈哈。
2、$statechangestart
路由状态变化发生前触发的事件。参数有:event,tostate,toparams,fromstate,fromparams。
3、$statechangesuccess
路由状态变化正确时触发的事件。参数有:event,tostate,toparams,fromstate,fromparams。
4、$statenotfound
路由状态没找到的时候触发的事件。参数有:event,unfoundstate,fromstate,fromparams。
$stateprovider
处理路由状态的服务,路由的状态反映了该项在应用程序中的位置,描述了在当前状态下ui是应该怎么样的,并且该做什么。
依赖:$urlrouterprovider $urlmatcherfactoryprovider
方法:
decorator(name,func);
通过内部的$stateprovider以扩展或者重写状态生成器。可用于添加ui-router的自定义功能,例如,基于状态名称推断templateurl。
警告:因为生成器的函数执行顺序的不确定,decorator不应该相互依赖。
参数:
代码:
$stateprovider.decorator('views', function (state, parent) { var result = {}, views = parent(state); angular.foreach(views, function (config, name) { var autoname = (state.name + '.' + name).replace('.', '/'); config.templateurl = config.templateurl || '/partials/' + autoname + '.html'; result[name] = config; }); return result; }); $stateprovider.state('home', { views: { 'contact.list': { controller: 'listcontroller' }, 'contact.item': { controller: 'itemcontroller' } } }); $state.go('home');
以上代码修饰了“views”直接通过state的名称绑定完对应的页面模板。
state(name,stateconfig);
注册一个状态,并给定其配置。
参数:
ui-sref
一种将链接(<a>标签)绑定到一个状态的指令。点击该链接将触发一个可以带有可选参数的状态转换。
代码:
<a ui-sref="app.index">首页</a> <!-- 这里是正常的跳转 --> <a ui-sref="app.index({id:yourid})">你的主页</a> <!-- 这里是带参数对象的跳转,名称是id,值是yourid -->
简单的使用代码(ui-router的单视图):
<div ng-app="demo" ng-controller="testctrl as ctrl"> <ol> <li><a ui-sref="app">app</a></li> <li><a ui-sref="test">test</a></li> </ol> <div ui-view></div> <script type="text/ng-template" id="'page1.html'"> this is page 1 for app. </script> <script type="text/ng-template" id="'page3.html'"> this is page 1 for test. </script> </div>
angular.module('demo', ['ui.router']) .config(["$stateprovider","$urlrouterprovider",routeconfig]) .controller("testctrl", angular.noop) function routeconfig($stateprovider,$urlrouterprovider){ $urlrouterprovider.otherwise("/app"); $stateprovider .state("app",{ url:"/app", templateurl:"'page1.html'" }) .state("test",{ url:"/test", templateurl:"'page3.html'" }) }
使用代码(ui-router的多视图):
<div ng-app="demo" ng-controller="testctrl as ctrl"> <ol> <li><a ui-sref="app.page1">app</a></li> <li><a ui-sref="test.page1({id:1})">test</a></li> </ol> <div ui-view></div> <script type="text/ng-template" id="'layout.html'"> <div ui-view="nav@"></div> <div ui-view></div> </script> <script type="text/ng-template" id="'nav1.html'"> <ol> <li><a ui-sref="app.page1">app.page1</a></li> <li><a ui-sref="app.page2">app.page2</a></li </ol> </script> <script type="text/ng-template" id="'nav2.html'"> <ol> <li><a ui-sref="test.page1({id:1})">test.page1</a></li> <li><a ui-sref="test.page2">test.page2</a></li </ol> </script> <script type="text/ng-template" id="'page1.html'"> this is page 1 for app. </script> <script type="text/ng-template" id="'page2.html'"> this is page 2 for app. </script> <script type="text/ng-template" id="'page3.html'"> this is page 1 for test. </script> <script type="text/ng-template" id="'page4.html'"> this is page 2 for test. </script> </div>
angular.module('demo', ['ui.router']) .config(["$stateprovider","$urlrouterprovider",routeconfig]) .controller("testctrl", angular.noop) function routeconfig($stateprovider,$urlrouterprovider){ $urlrouterprovider.otherwise("/app/page1"); $stateprovider .state("app",{ url:"/app", views:{ "":{ templateurl:"'layout.html'" }, "nav":{ templateurl:"'nav1.html'" } } }) .state("app.page1",{ url:"/page1", templateurl:"'page1.html'" }) .state("app.page2",{ url:"/page2", templateurl:"'page2.html'" }) .state("test",{ url:"/test", views:{ "":{ templateurl:"'layout.html'" }, "nav":{ templateurl:"'nav2.html'" } } }) .state("test.page1",{ url:"/page1?:id", templateurl:"'page3.html'", controller:["$stateparams",function($stateparams){ console.log($stateparams.id);// 1 这里实现传参 }], params:{ id:null } }) .state("test.page2",{ url:"/page2", templateurl:"'page4.html'" }) }
注意:需要引入angular-ui-router[.min].js
这里本兽没有也不会把全部用法写一遍 -。- 写两个简单的案例仅供学习参考。这里偷个懒,把代码都写在一个页面上完成了... 毕竟花了两个晚上的空闲时间用来整理内容和写demo 考虑到第二天要上班,都是尽量的早睡,所以整理资料拖的久了些。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。
如对本文有疑问, 点击进行留言回复!!
基于Angular 8和Bootstrap 4实现动态主题切换的示例代码
解决三元运算符 报错“SyntaxError: can''t assign to conditional expression”
解决angular 使用原生拖拽页面卡顿及表单控件输入延迟问题
使用 Angular RouteReuseStrategy 缓存(路由)组件的实例代码
分享Angular http interceptors 拦截器使用(推荐)
网友评论