次加载页面就下载好所有的资源没有什么大问题。但是当我们的网站渐渐庞大起来,这样子的加载策略让网速初始化速度变得越来越慢,用户体验不好。二来,分模块加载易于团队协作,减低代码冲突。
代码目录结构
html
-login.html
-register.html
js
-angular.min.js
-angular-ui-router.min.js
-ocLazyLoad.min.js
index.html
login.js
main.js
register.js
//index.html
<!DOCTYPE html>
<html lang="zh-cn" ng-app="test" id="test">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no">
<meta name="format-detection" content="telephone=no">
<title ng-bind="title"></title>
<script src="./js/angular.min.js"></script>
<script src="./js/angular-ui-router.min.js"></script>
<script src="./js/ocLazyLoad.min.js"></script>
<script src="./main.js"></script>
</head>
<body data-ng-controller="mainController">
<div class="main-view ng-cloak" data-ui-view="mainView" id="mainView" ng-cloak></div>
</body>
</html>
//main.js
var app = angular.module("test", ["ui.router", "oc.lazyLoad"])
.config(["$stateProvider", "$locationProvider", "$urlRouterProvider", "$ocLazyLoadProvider", function($stateProvider, r, s, $ocLazyLoadProvider) {
s.otherwise("/");
s.when("/", "/register");
r.hashPrefix("");
$ocLazyLoadProvider.config({
events : true
});
$stateProvider.state("register", {
title: "注册",
url: "/register",
views: {
mainView: {
templateUrl: "./html/register.html",
controller: "registerCtrl"
}
},
resolve: {
loadMyCtrl1: ["$ocLazyLoad", function(e) {
return e.load(["./register.js"])
}]
}
}).state("login", {
title: "登录",
url: "/login",
views: {
mainView: {
templateUrl: "./html/login.html",
controller: "loginCtrl"
}
},
resolve: {
loadMyCtrl1: ["$ocLazyLoad", function(e) {
return e.load(["./login.js"])
}]
}
});
}
]);
app.controller("mainController", ["$stateParams", "$rootScope", "$state", function(e, t, i) {}]);
//register.js
var app = angular.module("test");
app.controller("registerCtrl", ["$scope", "$state", "$ocLazyLoad", function($scope, $state, $ocLazyLoad) {
$scope.name = 'register';
$scope.goLogin = function(){
$state.transitionTo("register.index");
}
}]);
//register.html
<div>
注册:{{ name }}
<div ng-click="goLogin()">
我要登录
</div>
</div>
//login.js
var app = angular.module("test");
app.controller("loginCtrl", ["$scope", function($scope) {
$scope.name = 'login';
}]);
//login.html
<div>
登录:{{ name }}
</div>