这篇文章将为大家详细讲解有关AngularJS怎么通过ocLazyLoad实现动态懒加载模块和依赖,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
实现的过程主要是引用3个主要的JS文件:
<script src="angular/1.4.8/angular/angular.min.js"></script>
<script src="angular/ui-router/release/angular-ui-router.min.js"></script>
<script src="angular/oclazyload/src/ocLazyLoad.min.js"></script>
然后通过 APP 配置,将依赖的脚本进行注入操作:
var app = angular.module('pkcms', ["ui.router", "oc.lazyLoad"]);
app.config(["$provide", "$compileProvider", "$controllerProvider", "$filterProvider",
function ($provide, $compileProvider, $controllerProvider, $filterProvider) {
app.controller = $controllerProvider.register;
app.directive = $compileProvider.directive;
app.filter = $filterProvider.register;
app.factory = $provide.factory;
app.service = $provide.service;
app.constant = $provide.constant;
}]);
// 按模块化加载其他的脚本文件
app.constant('Modules_Config', [
{
name: 'treeControl',
serie: true,
files: [
"Scripts/angular-bootstrap/ui-bootstrap-tpls-0.14.3.min.js"
]<br>}]);
app.config(["$ocLazyLoadProvider","Modules_Config",routeFn]);
function routeFn($ocLazyLoadProvider,Modules_Config){
$ocLazyLoadProvider.config({
debug:false,
events:false,
modules:Modules_Config
});
};
以上是初始化动态加载的配置过程。
接着是建立路由:
"use strict"
app.config(["$stateProvider","$urlRouterProvider",routeFn]);
function routeFn($stateProvider,$urlRouterProvider){
$urlRouterProvider.otherwise("/main");
$stateProvider
.state("main",{
url:"/main",
templateUrl:"views/main.html",
controller:"mainCtrl",
controllerAs:"main",
resolve:{
deps:["$ocLazyLoad",function($ocLazyLoad){
return $ocLazyLoad.load("controllers/main.js");
}]
}
})
.state("adminUser",{
url:"/adminUser",
templateUrl:"views/adminUser.html",
controller:"adminUserCtrl",
controllerAs:"adminUser",
resolve:{
deps:["$ocLazyLoad",function($ocLazyLoad){
return $ocLazyLoad.load("controllers/adminUser.js");
}]
}
})
};
最后是按路由配置的在对应目录下建2个HTML页面文件和2个JS文件用做测试
main.html
<div>
{{main.value}}
</div>
adminUser.html
<div>
{{adminUser.value}}
</div>
main.js
(function () {
"use strict"
app.controller("mainCtrl", mainCtrlFn);
function mainCtrlFn() {
this.value = "Hello World";
}
}())
adminUser.js
(function () {
app.controller('adminUserCtrl',adminUserCtrlFn);
function adminUserCtrlFn() {
this.value = "welcome to admin user";
}
}());
关于“AngularJS怎么通过ocLazyLoad实现动态懒加载模块和依赖”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。