angularJs模組ui-router之狀態管理
ui-router 的工作原理非常類似於 Angular 的路由控制器,但它只關注狀態。
- 在應用程式的整個使用者介面和導航中,一個狀態對應於一個頁面位置
- 通過定義
controller
、template
和view
等屬性,來定義指定位置的使用者介面和介面行為 - 通過巢狀的方式來解決頁面中的一些重複出現的部位
最簡單的形式
模板可以通過下面這種最簡單的方式來指定
<!-- in index.html --> <body ng-controller="MainCtrl"> <section ui-view></section> </body>
// in app-states.js (or whatever you want to name it) $stateProvider.state('contacts', { template: '<h1>My Contacts</h1>' })
模板將被插入哪裡?
啟用狀態狀態被啟用時,它的模板會自動插入到父狀態對應的模板中包含ui-view
屬性的元素內部。如果是頂層的狀態,那麼它的父模板就是index.html
。
有三種方法來啟用狀態:
- 呼叫
$state.go()
方法,這是一個高階的便利方法; - 點選包含
ui-sref
指令的連結; - 導航到與狀態相關聯的 url。
Templates 模板
可以通過下面幾種方法來配置一個狀態的模板。
方法一:配置template
屬性,指定一段 HTML 字串,這人是設定模板的最簡單的方式
$stateProvider.state('contacts', { template: '<h1>My Contacts</h1>' })
方法二:配置templateUrl
屬性,來載入指定位置的模板,這是設定模板的常用方法。
$stateProvider.state('contacts', { templateUrl: 'contacts.html' })
templateUrl
的值也可以是一個函式返回的url,函式帶一個預設引數stateParams
$stateProvider.state('contacts', {
templateUrl: function (stateParams){
return '/partials/contacts.' + stateParams.filterBy + '.html';
}
})
方法三:通過
的值也可以是一個函式返回的url,函式帶一個預設引數templateProvider
函式返回模板的
HTML。templateUrlstateParams
。
$stateProvider.state('contacts', { templateProvider: function ($timeout, $stateParams) { return $timeout(function () { return '<h1>' + $stateParams.contactId + '</h1>' }, 100); } })
如果想在狀態被啟用前,讓<ui-view>
有一些預設的內容,當狀態被啟用之後預設內容將被狀態對應的模板替換。
<body> <ui-view> <i>Some content will load here!</i> </ui-view> </body>
Controllers 控制器
可以為模板指定一個控制器(controller)。警告:控制器不會被例項化如果模板沒有定義。
設定控制器:
$stateProvider.state('contacts', { template: '<h1>{{title}}</h1>', controller: function($scope){ $scope.title = 'My Contacts'; } })
如果在模組中已經定義了一個控制器,只需要指定控制器的名稱即可:
$stateProvider.state('contacts', { template: ..., controller: 'ContactsCtrl' })
使用controllerAs
語法:
$stateProvider.state('contacts', { template: ..., controller: 'ContactsCtrl as contact' })
對於更高階的需要,可以使用controllerProvider
來動態返回一個控制器函式或字串:
$stateProvider.state('contacts', {
template: ...,
controllerProvider: function($stateParams) {
var ctrlName = $stateParams.type + "Controller";
return ctrlName;
}
})
控制器可以使用$scope.on()
方法來監聽事件狀態轉換。
控制器可以根據需要例項化,當相應的scope
被建立時。例如,當用戶點選一個url手動導航一個狀態時,$stateProvider
將載入對應的模板到檢視中,並且將控制器和模板的scope
繫結在一起。
解決器 Resolve
可以使用resolve
為控制器提供可選的依賴注入項。
resolve
配置項是一個由key/value
構成的物件。
- key – {string}:注入控制器的依賴項名稱。
- factory - {string|function}:
- string:一個服務的別名
- function:函式的返回值將作為依賴注入項,如果函式是一個耗時的操作,那麼控制器必須等待該函式執行完成(be resolved)才會被例項化。
例子
在controller
例項化之前,resolve
中的每一個物件都必須 be resolved,請注意每個 resolved object 是怎樣作為引數注入到控制器中的。
$stateProvider.state('myState', { resolve:{ // Example using function with simple return value. // Since it's not a promise, it resolves immediately. simpleObj: function(){ return {value: 'simple!'}; }, // Example using function with returned promise. // 這是一種典型使用方式 // 請給函式注入任何想要的服務依賴,例如 $http promiseObj: function($http){ // $http returns a promise for the url data return $http({method: 'GET', url: '/someUrl'}); }, // Another promise example. // 如果想對返回結果進行處理, 可以使用 .then 方法 // 這是另一種典型使用方式 promiseObj2: function($http){ return $http({method: 'GET', url: '/someUrl'}) .then (function (data) { return doSomeStuffFirst(data); }); }, // 使用服務名的例子,這將在模組中查詢名稱為 'translations' 的服務,並返回該服務 // Note: The service could return a promise and // it would work just like the example above translations: "translations", // 將服務模組作為解決函式的依賴項,通過引數傳入 // 提示:依賴項 $stateParams 代表 url 中的引數 translations2: function(translations, $stateParams){ // Assume that getLang is a service method // that uses $http to fetch some translations. // Also assume our url was "/:lang/home". translations.getLang($stateParams.lang); }, // Example showing returning of custom made promise greeting: function($q, $timeout){ var deferred = $q.defer(); $timeout(function() { deferred.resolve('Hello!'); }, 1000); return deferred.promise; } }, // 控制器將等待上面的解決項都被解決後才被例項化 controller: function($scope, simpleObj, promiseObj, promiseObj2, translations, translations2, greeting){ $scope.simple = simpleObj.value; // 這裡可以放心使用 promiseObj 中的物件 $scope.items = promiseObj.items; $scope.items = promiseObj2.items; $scope.title = translations.getLang("english").title; $scope.title = translations2.title; $scope.greeting = greeting; } })
為 $state 物件提供自定義資料
可以給 $state 物件提供自定義資料(建議使用data
屬性,以免衝突)
// 基於物件和基於字串定義 state 的例子 var contacts = { name: 'contacts', templateUrl: 'contacts.html', data: { customData1: 5, customData2: "blue" } } $stateProvider .state(contacts) .state('contacts.list', { templateUrl: 'contacts.list.html', data: { customData1: 44, customData2: "red" } })
可以通過下面的方式來訪問上面定義的資料:
function Ctrl($state){ console.log($state.current.data.customData1) // 輸出 5; console.log($state.current.data.customData2) // 輸出 "blue"; }
onEnter 和 onExit 回撥函式
onEnter
和onExit
回撥函式是可選配置項,分別稱為當一個狀態變得活躍的和不活躍的時候觸發。回撥函式也可以訪問所有解決依賴項。
$stateProvider.state("contacts", { template: '<h1>{{title}}</h1>', resolve: { title: 'My Contacts' }, controller: function($scope, title){ $scope.title = 'My Contacts'; }, // title 是解決依賴項,這裡也是可以使用解決依賴項的 onEnter: function(title){ if(title){ ... do something ... } }, // title 是解決依賴項,這裡也是可以使用解決依賴項的 onExit: function(title){ if(title){ ... do something ... } } })
State Change Events 狀態改變事件
所有這些事件都是在$rootScope
作用域觸發
- $stateChangeStart - 當模板開始解析之前觸發
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){ ... })
注意:使用event.preventDefault()
可以阻止模板解析的發生
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){ event.preventDefault(); // transitionTo() promise will be rejected with // a 'transition prevented' error })
- $stateNotFound -
v0.3.0
- 在 transition 時通過狀態名查詢狀態,當狀態無法找到時發生。該事件在 scope 鏈上廣播,只允許一次處理錯誤的機會。unfoundState
將作為引數傳入事件監聽函式,下面例子中可以看到unfoundState
的三個屬性。使用event.preventDefault()
來阻止模板解析,
// somewhere, assume lazy.state has not been defined $state.go("lazy.state", {a:1, b:2}, {inherit:false}); // somewhere else $scope.$on('$stateNotFound', function(event, unfoundState, fromState, fromParams){ console.log(unfoundState.to); // "lazy.state" console.log(unfoundState.toParams); // {a:1, b:2} console.log(unfoundState.options); // {inherit:false} + default options })
- $stateChangeSuccess - 當模板解析完成後觸發
$rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){ ... })
- $stateChangeError - 當模板解析過程中發生錯誤時觸發
$rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState, fromParams, error){ ... })
View Load Events 檢視載入事件
$viewContentLoading - 當檢視開始載入,DOM渲染完成之前觸發,該事件將在$scope
鏈上廣播此事件。
$scope.$on('$viewContentLoading', function(event, viewConfig){ // Access to all the view config properties. // and one special property 'targetView' // viewConfig.targetView });
- $viewContentLoaded - 當檢視載入完成,DOM渲染完成之後觸發,檢視所在的
$scope
發出該事件。
$scope.$on('$viewContentLoading', $scope.$on('$viewContentLoaded', function(event){ ... });