參考原文:https://github.com/angular-ui/ui-router/wiki
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';
}
})
方法三:通過templateProvider函數返回模板的 HTML。
$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){ ... });
轉載自http://bubkoo.com/2014/01/01/angular/ui-router/guide/state-manager/