摘要:[MAN铁人赛]Day 07:AngularJS - Plugin:UI-Router
A -> AngularJS - Plugin:UI-Router
前言
在昨天介绍的Routing中,让大家对换页有基本的概念后就要来介绍这个AngularJS上必装超强的plugin:UI-Router。
UI-Router
github
UI-Router是AngularJS的一个routing framework,主要是帮助你可以有架构将你的页面分开成不同的子页面呈现Nested view,不同于原本的$route service,UI-Router 是一个透过state的架构来切换页面,这让你有更大的弹性来切换你的页面。
使用方式如下:
... ...
范例
范例
首先在结构上总共有五个页面,页面上大致说明如下
- index.html
范例首页,载入所有css,js与设定ng-app的应用范围,重点设定如下:
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/1.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"]; } }) });
这边透过设定每个state对应的url中的templateUrl与controller来分配连接版面与各版面操控的内容。
- route1.html
当url指到#/route1时显示的页面,里面包含一个子状态的设定显示route1.list.html的内容,url指到#/route2时显示的页面,里面包含一个子状态的设定显示route2.list.html的内容,源代码如下:
Route 1 Show List Route 2 Show List
这边透过ui-sref的方式指定Show List的内容来自于各自文件名接上.list之后的html页面内容。
-
route1.list.html与route2.list.html
List of State 1 Items
- {{ item }}
h3>List of State 2 Things
- {{ thing }}
这边透过ngRepeat的方式分别读出item与thing内的对象
结语
介绍到这边,基本上大家已经可以建立一个简单地SPA网页,接下来就要再一一介绍AngularJS各项强大的火力给大家认识了!Day-8 over!

原文:大专栏 [MAN铁人赛]Day 08:AngularJS - Plugin:UI-Router