ui-router中使用ocLazyLoad和resolve的具體方法
1.AngularJS按需加載
AngularJS主要應(yīng)用開發(fā)SPA(Single Page Application)項(xiàng)目,所以在小型項(xiàng)目中,services、filters和controllers都在index.html中加載。Google給的AngularJS官方的angular-seed和angular-phonecat都是這樣。
對(duì)于復(fù)雜一點(diǎn),大型的項(xiàng)目,如果所有的內(nèi)容一開始就加載,對(duì)首頁的性能影響比較大,即使靜態(tài)javascript文件使用CDN,對(duì)性能還是有很大的影響。所有需要引入按需加載機(jī)制,而Angular1.x版本中,ocLazyLoad是一個(gè)不錯(cuò)的按鈕加載解決方案。
2.ocLazyLoad的功能
ocLazyLoad: your solution for lazy loading with Angular 1.x
入門可以參照:ocLazyLoad快速入門,代碼也非常簡單:
1.引入ocLazyLoad文件,可以使用npm和bower來進(jìn)行安裝
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.min.js"></script> <script src="libs/angular-ui-router/angular-ui-router.js"></script> <script src="libs/ocLazyLoad/ocLazyLoad.js"></script>
2.注入 oc.lazyLoad模塊
var myApp = angular.module("MyApp", ["oc.lazyLoad"]);
3. 在控制器中加載一個(gè)指定的模塊
myApp.controller("MyCtrl", function($ocLazyLoad) {
$ocLazyLoad.load('testModule.js');
});
在實(shí)際項(xiàng)目中service和controller文件都是通過ocLazyLoad加載,并且是放在resolve中加載。代碼示例如下:
.state('detail',{
url:"/detail/:bookId",
templateUrl:"/templates/detail.html",
controller:"DetailController",
controllerAs:'ctrl',
resolve:{
load:['$ocLazyLoad',function($ocLazyLoad){
return $ocLazyLoad.load([
'services/dataService.js'
]);
}],
currentBook:['$ocLazyLoad','$stateParams','$injector',function($ocLazyLoad,$stateParams,$injector){
var bookId=$stateParams.bookId;
return $ocLazyLoad.load('services/booksService.js').then(function(){
return $injector.get('booksService').getBookById(bookId);;
});
}]
}
})
3.resolve屬性
resolve在state配置參數(shù)中,是一個(gè)對(duì)象(key-value),每一個(gè)value都是一個(gè)可以依賴注入的函數(shù),并且返回的是一個(gè)promise(當(dāng)然也可以是值,resloved defer)。
4.resolve中加載service
resolve中加載services,但是請(qǐng)求都是異步的,返回的順序不是按照順序來的。在currentBook中需要調(diào)用booksService里面的getBookById()方法。這個(gè)時(shí)候雖然在load里面已經(jīng)加載dataService.js,但是在currentBook中是無法使用getBookById()方法,所以在currentBook對(duì)象中,所以必須重新加載booksService.js。這個(gè)時(shí)候就需要$injector中的get()方法。$injector
5.圖書列表和詳細(xì)頁demo

6.參考網(wǎng)址
綜合示例:http://www.dhdzp.com/article/92624.htm
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
詳解AngularJS中$http緩存以及處理多個(gè)$http請(qǐng)求的方法
$http 是 AngularJS 中的一個(gè)核心服務(wù),用于讀取遠(yuǎn)程服務(wù)器的數(shù)據(jù),通過本文給大家介紹AngularJS中$http緩存以及處理多個(gè)$http請(qǐng)求的方法,希望的朋友一起學(xué)習(xí)吧2016-02-02
Angular2.0實(shí)現(xiàn)modal對(duì)話框的方法示例
這篇文章主要介紹了Angular2.0實(shí)現(xiàn)modal對(duì)話框的方法,結(jié)合實(shí)例形式分析了angular2.0實(shí)現(xiàn)modal對(duì)話框的樣式、界面及功能等相關(guān)操作技巧,需要的朋友可以參考下2018-02-02
AngularJS+Bootstrap3多級(jí)導(dǎo)航菜單的實(shí)現(xiàn)代碼
將介紹如何用AngularJS構(gòu)建一個(gè)強(qiáng)大的web前端系統(tǒng)。文章介紹如何實(shí)現(xiàn)多限級(jí)導(dǎo)航菜單。本文圖文并茂給大家介紹的非常詳細(xì),感興趣的朋友參考下吧2017-08-08
AngularJS與后端php的數(shù)據(jù)交互方法
今天小編就為大家分享一篇AngularJS與后端php的數(shù)據(jù)交互方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-08-08

