我們了解 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表示指令鏈接到一個特定的狀態,一般情況下為替換視圖,替換視圖的部分為使用<ui-view></ui-view>
所標記的區域??梢院唵蔚睦斫鉃?code><ui-view></ui-view> 起到的其實是一個占位符的作用。
接下來咱們再看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'
模塊,在angular對象的配制方法中,我們通過 ui-router提供的$stateProvider對象的 state方法去配置路由對象,name對應ui-sref中配置的值,使用template去替換<ui-view></ui-view>
。
那么ui-router中的嵌套路由是如何使用的呢?來看我們修改之后的代碼。
.state('world',{ url:'/world', templateUrl:'world.html' })我們對index.js進行了修改,使點擊world的之后指向了一個 world.html
的模板。
這是world.html中的代碼,我們可以看到在world.html中我們創建了兩個 ui-sref 分別為:.world1和world2
,相信看到這里大家也都能知道了,ui-router其實就是通過 .語法 去進行的路由層級的配置。 來看一下新的 index.js的代碼。
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>新聞熱點
疑難解答