AngularJs学习之ui-router深入 《组件》

angular ui-router 官方文档:https://github.com/angular-ui/ui-router/wiki/URL-Routing

以下摘抄一段网上关于ui-router的解释(没搞懂)

这个库提供了针对视图的众多的额外控制,我们可以创建嵌套的视图,在单个页面使用多个视图,多个视图来控制单个视图,还有更多特性。对于更加精细的控制和更为复杂的应用,ui-router 是非常棒的工具。

ui-router 从状态着手来管理路由,它将应用视为多个状态的组合,通过状态的切换进行路由。

  • 一个状态可以对应一个页面地址,通过特定的地址到达应用的特定状态。
  • 通过状态的 controller、template 和 views 来管理特定状态的 UI 和行为
  • 通过嵌套视图来解决页面中重复出现的内容。

然后自己查阅并翻译ui-router 官方文档

Most states in your application will probably have a url associated with them. URL Routing was not an afterthought to the state mechanics, but was figured into the design from the beginning (all while keeping states separate from url routing)

Here's how you set a basic url.

$stateProvider
    .state('contacts', {
        url: "/contacts",
        templateUrl: 'contacts.html'
    })

Now when the user accesses index.html/contacts then the 'contacts' state would become active and the main ui-view will be populated with the 'contacts.html' partial. Alternatively, if the user were to transition to the 'contacts' state via transitionTo('contacts') then the url would be updated to index.html/contacts

总结一下

        在ui-router里,应用的每个状态都绑定一个url(与以前的url跳转方式有所不同,可以理解ui-router每个路由对应一个页面,类似ngRoute路由机制),并将状态与路由分开。当用户访问index.html/contacts,‘contacts’这个状态将被激活,那么页面中包含‘ui-view’的标签将被部分填充contact.html(注:templateUrl加载模块时注意项目需要在服务器环境运行,本地运行有坑),状态之间的过渡则可以理解为url跳转。

ngRoute 与 ui-router 区别:

    1 ng-route的局限性:一个页面无法嵌套多个视图,也就是说一个页面只能有包含一个页面一个控制器的切换。

    2 ui-route的改进:在具有富客户端的单页应用中,要在一个页面中呈现不同的视图,我们可以通过ui-route实现路由的嵌套。例如:通过ng-view指令加载一个控制面板页面后,如果想添加子视图,ngRouter模块就不支持,此时ui-router可以实现。

示例代码:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>ui-router</title>
	<script src="../../js/lib/angular.min.js"></script>
	<script src="../../js/lib/angular-ui-router.min.js"></script>
</head>
<body ng-app="myApp">
	<div ui-view>
	</div>
	<script type="text/javascript">
		'use strict';
		var app = angular.module('myApp',['ui.router']);
		app.config(['$stateProvider','$urlRouterProvider',function($stateProvider,$urlRouterProvider) {
			$urlRouterProvider.when('','/index');// 路由为空,则跳转index
			$urlRouterProvider.otherwise('/index');// 无效路由,则跳转index
			$stateProvider
			.state("index", {
				url: '/index',
				template: "<div>这是index路由</div>"
			})
			.state("home", {
				url: '/home',
				template: "<div>这是路由</div>"
			})
			.state("home1", {
				url: '/home1',
				template: "<div>这是路由1</div>"
			})
			.state("home2", {
				url: '/home2',
				templateUrl: 'template1.html',
			})
		}])
	</script>
</body>
</html>

路由1:..index.html#/index

路由2:..index.html#/home

路由3:..index.html#/home1

路由4:..index.html#/home2 (templateUrl加载需要在服务器环境)

猜你喜欢

转载自blog.csdn.net/wq18512847606/article/details/79614929