ui-router
#AngularUI Router
AngularJS 不提供模板视图的嵌套功能,而 ui-router 很好的解决了这一问题。
获取ui-router
clone & build this repository download the release (or minified)
Bower: $ bower install angular-ui-router from your console
npm: $ npm install angular-ui-router from your console
Component: $ component install angular-ui/ui-router from your console
引用文件并添加到 module 中
<!doctype html>
<html ng-app="myApp">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>
<script src="js/angular-ui-router.min.js"></script>
<script>
var myApp = angular.module('myApp', ['ui.router']);
// For Component users, it should look like this:
// var myApp = angular.module('myApp', [require('angular-ui-router')]);
</script>
...
</head>
<body>
...
</body>
</html>
使用 ui-view 指令替换原来的 ng-view
在 ui-router 中使用 state 来进行 route 的切换,在 a 标签上使用 ui-sref 并能链接指向相应的 state
<body>
<div ui-view></div>
<!-- We'll also add some navigation: -->
<a ui-sref="state1">State 1</a>
<a ui-sref="state2">State 2</a>
</body>
<!-- partials/state1.html -->
<h1>State 1</h1>
<!-- partials/state2.html -->
<h1>State 2</h1>
在 app config 中使用 $stateProvider 来配置需要的 state
myApp.config(function($stateProvider, $urlRouterProvider) {
// For any unmatched url, redirect to /state1
$urlRouterProvider.otherwise("/state1");
//
// Now set up the states
$stateProvider
.state('state1', {
url: "/state1",
templateUrl: "partials/state1.html"
})
.state('state2', {
url: "/state2",
templateUrl: "partials/state2.html"
});
});
通过上面两步就可以实现与 angularjs $routeProvider 同样的功能,但在 ui-router 中还可以实现 view 和 state 的嵌套
<!-- partials/state1.html -->
<h1>State 1</h1>
<hr/>
<a ui-sref="state1.list">Show List</a>
<div ui-view></div>
<!-- partials/state2.html -->
<h1>State 2</h1>
<hr/>
<a ui-sref="state2.list">Show List</a>
<div ui-view></div>
<!-- partials/state1.list.html -->
<h3>List of State 1 Items</h3>
<ul>
<li ng-repeat="item in items"></li>
</ul>
<!-- partials/state2.list.html -->
<h3>List of State 2 Things</h3>
<ul>
<li ng-repeat="thing in things"></li>
</ul>
myApp.config(function($stateProvider, $urlRouterProvider) {
//
// For any unmatched url, redirect to /state1
$urlRouterProvider.otherwise("/state1");
//
// Now set up the states
$stateProvider
.state('state1', {
url: "/state1",
templateUrl: "partials/state1.html"
})
.state('state1.list', {
url: "/list",
templateUrl: "partials/state1.list.html",
controller: function($scope) {
$scope.items = ["A", "List", "Of", "Items"];
}
})
.state('state2', {
url: "/state2",
templateUrl: "partials/state2.html"
})
.state('state2.list', {
url: "/list",
templateUrl: "partials/state2.list.html",
controller: function($scope) {
$scope.things = ["A", "Set", "Of", "Things"];
}
});
});
上面的代码是一个简单的嵌套例子,在 $stateProvider 中配置的 state1.list 和 state2.list 都输出到 state1 和 state2 对应的视图 state1.html 和 state2.html 中的 ui-view 指令标签里