/static/css/sweeta" />
AngularJS+RequireJs实现动态加载JS和页面的方案研究
1、入口页面
存放地址:src/main/webapp/WEB-INF/view/workflow/workflow.jsp
[html] view plain copy 在CODE上查看代码片派生到我的代码片
在上面引入了requirejs
2、app.js
[html] view plain copy 在CODE上查看代码片派生到我的代码片
require.config({
paths: {
"angular": "../angular/1.5.3/angular.min",
"angular-messages":"../angular/1.5.3/angular-messages.min",
"angular-locale_zh-cn":"../angular/1.5.3/angular-locale_zh-cn",
"angular-ui-router":
"../bower_components/angular-ui-router/release/angular-ui-router",
"angularAMD": "../bower_components/angularAMD/angularAMD",
"ngload": "../bower_components/angularAMD/ngload",
"sweetalert": "../sweetalert/sweetalert.min",
"uiBootstrap": "../angular-ui-bootstrap/1.2.4/ui-bootstrap-tpls-1.2.4.min",
"commonFunction":"../angularCommon/commonFunction",
"commonValueAndUrl":"../angularCommon/commonValueAndUrl",
"workFlowCommonModule":"../angularCommon/workFlowCommonModule"
},
shim: {
"angular": { exports: "angular" },
"workFlowCommonModule": ["angular"],
"angular-messages": ["angular"],
"angular-locale_zh-cn": ["angular"],
"commonValueAndUrl": ["commonFunction"],
"angular-ui-router": ["angular"],
"uiBootstrap": ["angular-ui-router"],
"angularAMD": ["angular"],
"ngload": ["angularAMD"]
}
});
define(["angular", "angularAMD", "angular-ui-router","sweetalert","uiBootstrap","angular-messages","angular-locale_zh-cn","com monFunction","commonValueAndUrl","workFlowCommonModule"], function (angular, angularAMD) {
var registerRoutes = function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/home");
$stateProvider.state("home", angularAMD.route({
url: "/home",
templateUrl: "../static/js/workflow-view/home-view.js",
controllerUrl: "../static/js/workflow/home.js"
}))
.state("about", angularAMD.route({
url: "/about",
templateUrl: "../static/js/workflow-view/about-view.js",
controllerUrl: "../static/js/workflow/about.js"
}))
;
};
var app = angular.module("app", ["ui.router",'ui.bootstrap','ngMessages','commonModule']);
app.config(["$stateProvider", "$urlRouterProvider", registerRoutes]);
app.controller('baseCtrl',function($scope,$uibModal,sendAjaxFactory) {
$scope.baseClick = function () {
swal("测试按钮")
}
});
return angularAMD.bootstrap(app);
});
在这里引入了一些需要的模块,其中就一些模块是笔者我自己写的。有的是第三方插件的这里特别注意,由于SpringMVC会拦截.jsp结尾的文件。所以动态加载的页面笔者都写到js文件中。如上面的about-view.js和home-view.js.其要动态加载的js文件分别为about.js 和home.js。如果不使用SpringMVc。那么动态加载的页面就可以不用写到js文件中(笔者的工程中配置了拦截.jsp文件,不拦截.js文件)
3、动态加载的内容:
home.js
[html] view plain copy 在CODE上查看代码片派生到我的代码片
define(['app'], function(app)
{
app.controller('HomeViewController',
['$scope',function($scope) {
document.getElementById("test").onclick = function(){
swal($scope.title);
}
$scope.title = "Home Home Home Home";
}
]);
});
home-view.js
[html] view plain copy 在CODE上查看代码片派生到我的代码片