UI-Router详解
我们了解 angular.js 是一种富客户端单页面应用,所以要在一个页面呈现不同的视图,路由起到了至关重要的作用. angular.js :为我们封装好了一个路由工具 ngRoute,它是一种靠url改变去驱动视图. angularUI :也为我们封装了一个独立的路由模块 ui-router,它是一种靠状态 state 来驱动视图. 后者有什么优势:一个页面可以嵌套多个视图,多个视图去控制某一个视图等. 咱们今天主要讲解ui-router的基本模块,先上代码。 <!DOCTYPE html>
<html lang="en" ng-app="sunday">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<a ui-sref="hello" ui-sref-active="active">hello</a>
<br>
<a ui-sref="world" ui-sref-active="active">world</a>
<ui-view></ui-view>
<script src="js/angular.js"></script>
<script src="js/angular-ui-router.js"></script>
<script src="js/index.js"></script>
</body>
</html>
基本的index.html,ui-sref表示指令链接到一个特定的状态,一般情况下为替换视图,替换视图的部分为使用 接下来咱们再看js代码。 (function(angular){ angular.module('sunday',['ui.router']) .config(function($stateProvider){ $stateProvider.state({ name:'hello',url:'/hello',template:'<h3>hello world!</h3>' }).state({ name:'world',url:'/world',template:'<h3>hello ui-router!</h3>' }) }); })(angular);
在构造angular对象的时候,我们引入了 那么ui-router中的嵌套路由是如何使用的呢?来看我们修改之后的代码。 .state('world',{
url:'/world',templateUrl:'world.html'
})
我们对index.js进行了修改,使点击world的之后指向了一个 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>This is a world</title>
</head>
<body>
<div>
<a ui-sref=".world1" ui-sref-active="active">world-1</a>
<br>
<a ui-sref="world2" ui-sref-active="active">world-2</a>
</div>
<div ui-view style="margin-left: 50px"></div>
</body>
</html>
这是world.html中的代码,我们可以看到在world.html中我们创建了两个 ui-sref 分别为: (function(angular){ angular.module('sunday',['ui.router']) .config(function($stateProvider){ $stateProvider.state('hello-world',{ url:'/hello',template:'<h3>hello world!</h3>' }).state('world',{ url:'/world',templateUrl:'world.html' }).state('world.world1',{ url:'/world/world-1',template:'<h3>This is a World 1</h3>' }).state('world2',{ url:'/world/world-2',template:'<h3>world2并不依赖于world,在我们点击它的时候,他会替换掉index.html中的<div ui-view></div></h3>' }) }); })(angular);
index.html的代码 <!DOCTYPE html>
<html lang="en" ng-app="sunday">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style> </style>
</head>
<body>
<a ui-sref="hello-world" ui-sref-active="active">hello</a>
<br>
<a ui-sref="world" ui-sref-active="active">world</a>
<div ui-view style="margin-left: 50px"></div>
<script src="js/angular.js"></script>
<script src="js/angular-ui-router.js"></script>
<script src="js/index.js"></script>
</body>
</html>
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |