Angularjs中UI Router的使用方法

学习使用angular中,ui-route是其中的一个难点,简单使用没什么问题,但涉及到多级嵌套,就感觉有茫然,查了很多资料,踩过很多坑,到目前为止也不能说对ui-route有全面了解;这里只是把填补的几个坑记录一下备忘:

1.abstract的使用:

$stateProvider .state('shop',{ resolve:{ "shoplist":function($http){ return $http({ url:"/bookApp/data/shoplist.php", method:"GET" }) } }, abstract: true, url:"/shop", templateUrl:"templates/shop/list.html", controller:"ShopListController" })

使用abstract属性有什么用,官方说明:abstract: true 表明此状态不能被显性激活,只能被子状态隐性激活。不能显性激活即不能直接通过"/shop"访问此状态路由,那不就是一条死路吗?那要你何用。等等,我们再看看后面一句:能被子状态隐性激活,貌似还能活起来,怎么让他活起来?我们再看下面的代码:

.state('shop.main',{ url:"/:id", abstract: true, templateUrl:"templates/shop/main2.html", controller:"ShopMainController" })

状态:"shop.main"是shop的子状态,按理论shop.main可以激活shop,我们只需要这样去访问:/shop/1,这样我们可以激活shop状态,和"shop.main"

我们暂且不着急,我再再给加上abstract属性,玩点刺激的,我们再把激活点再往后一级看下面代码:

.state('shop.main.info',{ url:"", templateUrl:"templates/shop/info.html", cache:'false', controller:"InfoController" }) .state('shop.main.author',{ url:"/author", template:"<div>authorauthorauthorauthorauthor</div>" }) .state('shop.main.samebook',{ url:"samebook", template:"<div>samebooksamebooksamebooksamebooksamebooksamebook</div>" })

我看状态"shop.main.info"这个状态 的url为""所以我们要激活这个状态只需要这样去访问"shop/1"所有可以做为"shop.main"的一个默认子状态。

此时模块的嵌套关系为:list.html嵌套main.html,main.html嵌套info.html。我们可以通过"shop/:id"的url激活这个三层嵌套。

2控制器中参数的使用:

这个没什么难点,在控制器中注入"$stateParams" url参数在这个对象里可以拿得到 :

shop.controller("ShopMainController",['$scope','$stateParams','$rootScope',function($scope,$stateParams,$rootScope){ $scope.persons = [1,2,3,4,5,6]; $scope.good = { id:$stateParams.id } cfpLoadingBar.start(); }]);

3.怎么防止模板缓存

在开发过程中,模板缓存严重影响我们调试,有时候代码修改了,模板却没有任何变化。很苦恼,其他我们只需要监听下stateChangeSuccess,然后再清除$templateCache就行,这里我们采用run方法添加监听:

bookApp.run(['$rootScope','$templateCache', function ($rootScope, $templateCache) { var stateChangeSuccess = $rootScope.$on('$stateChangeSuccess', stateChangeSuccess); function stateChangeSuccess($rootScope) { $templateCache.removeAll(); } }]);

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wzpxyp.html