项目结构
.
├── README.md
├── app
│ ├── index.html
│ └── single.html
└── js
├── angularjs
│ ├── angular-1.5.8.min.js
│ ├── angular-route.js
│ ├── angular-ui-router.js
│ ├── angular-ui-router.min.js
│ └── ocLazyLoad.min.js
├── app.js
└── singlecontroller.js
核心,按需求加载文件,对route进行重定义(app.js)
var App = angular.module('AppConfigService', ['ui.router', 'oc.lazyLoad']);
App.provider('appConfig', ['$stateProvider', '$urlRouterProvider', '$ocLazyLoadProvider', function ($stateProvider, $urlRouterProvider, $ocLazyLoadProvider) {
this.module = function (modules) {
$ocLazyLoadProvider.config({modules: modules});
};
this.otherwise = function (url) {
$urlRouterProvider.otherwise(url);
return this;
};
this.state = function (stateObj) {
var deps = [];
if (stateObj.deps) {
deps = stateObj.deps.names;
if (!deps)
deps = [];
if (stateObj.deps.files && stateObj.deps.files.length)
deps.push(
{
name: 'BayerApp',
serie: true,
insertBefore: '#ng_load_plugins_before', // load the above css files before '#ng_load_plugins_before'
files: stateObj.deps.files
});
}
$stateProvider.state(stateObj.name, {
url: stateObj.url,
templateUrl: stateObj.templateUrl || 'views/' + stateObj.name + '.html',
controller: stateObj.controller,
resolve: {
loadFiles: ['$ocLazyLoad', function ($ocLazyLoad) {
return $ocLazyLoad.load(deps);
}]
}
});
return this;
};
this.$get = function () {
return null;
}
}]);
注入创建的服务,并使用(app.js):
var AppConfig = angular.module('BayerApp', ['AppConfigService']);
AppConfig.config(['appConfigProvider', function (appConfigProvider) {
appConfigProvider.module([]);
appConfigProvider
.otherwise('/single')
.state({
name: 'single',
url: '/single',
templateUrl: 'spa/views/single.html',
controller: "SingleController",
deps: {
names: [],
files: [
'spa/controllers/singlecontroller.js'
]
}
})
}]);
增加一个controller(app.js):
App.controller("SingleController", function ($scope, $http) {
$scope.controller = function () {
alert('angular controller.');
};
});
html界面
<!DOCTYPE html>
<html lang="en" ng-app="BayerApp">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- angular -->
<script src="../js/angularjs/angular-1.5.8.min.js"><//script>
<script src="../js/angularjs/angular-route.js"><//script>
<script src="../js/angularjs/angular-ui-router.js"><//script>
<script src="../js/angularjs/ocLazyLoad.min.js"><//script>
<script src="../js/app.js"><//script>
</head>
<body>
<div ui-view>hello angular!</div>
</body>
</html>
singlecontroller.js
function hello() {
alert("hello!");
}
运行,即可。