AngularJS+RequireJs实现动态加载JS和页面的方案研究

摘要:本文是笔者研究了几天的动态加载方案的成果,前台使用的是AngularJS+RequireJs+angular-ui-router+angularAMD。后台使用了SpringMVC+Spring。

1、入口页面

存放地址:src/main/webapp/WEB-INF/view/workflow/workflow.jsp

<!DOCTYPE html>
<html lang="zh">
<head>	  
	<Meta charset="UTF-8">
	<title></title>
	<link href="<%=request.getContextPath()%>/static/css/bootstrap/3.3.5/bootstrap.min.css" rel="stylesheet">
    <link href="<%=request.getContextPath()%>/static/css/sweetalert/sweetalert.css" rel="stylesheet" >
    <link href="<%=request.getContextPath()%>/static/css/angularCommon.css" rel="stylesheet" >
	<script data-main="<%=request.getContextPath()%>/static/js/workflow/app.js" src="<%=request.getContextPath()%>/static/js/bower_components/requirejs/require.js"></script>
</head>
<body>
<div>
<h1>这里是公共头部</h1>
</div>
<div ng-controller = "baseCtrl">
<!--     <button ng-click = "baseClick()">按钮测试</button> -->
	<div ui-view></div>	
</div>
<div>
<h1>这里是公共尾部</h1>
    <button id = "test">根据js内容动态显示</button>
</div>
</body>
</html>
在上面引入了requirejs

2、app.js

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","commonFunction","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

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

<div ng-controller="HomeViewController">
<button ui-sref="about">About</button>
<h1>{{ title }}</h1>
<br/>
                   <form name = "registerForm" id = "registerForm" method="post" class="form-horizontal" novalidate >
                       <p class="bg-warning" style = "margin-left:50px;margin-right:50px;"><i class="glyphicon glyphicon-info-sign"></i><span > <b>温馨提示:带<span style="color:red">*</span>为必填项</b></span></p>
                       <div>
								<div class="form-group" style = "margin-left:50px;margin-right:-250px;">
									<label class="control-label col-md-1" for="merchantName">商户名称<span style="color:red">*</span></label>
									<div class="col-md-2" show-errors>
										<input type="text" class="form-control" id="merchantName" name = "merchantName" ng-model="merhantBaseInfo.merchantName" required>
                                        <div class="help-block" ng-messages="registerForm.merchantName.$error" ng-if="registerForm.merchantName.$touched">
							                <span ng-message="required" >用户名不能为空</span>
					                	</div>
									</div>
									<label class="control-label col-md-1" for="merchantShortName">商户简称</label>
									<div class="col-md-2" >
										<input type="text" class="form-control" id="merchantShortName" name ="merchantShortName"  ng-model="merhantBaseInfo.merchantShortName"  >
									</div>
									<label class="control-label col-md-1" for="type">商户类型<span style="color:red">*</span></label>
									<div class="col-md-2" show-errors>
										 <select  class="form-control" id="type" name = "type" ng-model="merhantBaseInfo.type"  ng-options="type.name as type.desc for type in MerchantTypeArray" required >
                                           <option value="">-- 请选择 --</option>
                                         </select>
                                         <div class="help-block" ng-messages="registerForm.type.$error" ng-if="registerForm.type.$touched">
							                <span ng-message="required" >商户类型不能为空</span>
					                     </div>
									</div>
								</div>
								<div class="form-group" style = "margin-left:50px;margin-right:-250px;">
									<label class="control-label col-md-1" for="comRegName">商户工商注册全名<span style="color:red">*</span></label>
									<div class="col-md-5" show-errors>
										<input type="text" class="form-control" id="comRegName" name = "comRegName" ng-model="merhantBaseInfo.comRegName" required>
                                        <div class="help-block" ng-messages="registerForm.comRegName.$error" ng-if="registerForm.comRegName.$touched">
							                <span ng-message="required" >商户注册全名不能为空</span>
					                	</div>
									</div>
									<label class="control-label col-md-1" for="industry">所属行业<span style="color:red">*</span></label>
									<div class="col-md-2" show-errors>
										<select  class="form-control" id="industry" name = "industry" ng-model="merhantBaseInfo.industry" ng-options="industry.name as industry.desc for industry in IndustryArray" required>
                                            <option value="">-- 请选择 --</option>
                                         </select>
                                        <div class="help-block" ng-messages="registerForm.industry.$error" ng-if="registerForm.industry.$touched">
							                <span ng-message="required" >所属行业不能为空</span>
					                	</div>
									</div>
								</div>
								<div class="form-group" style = "margin-left:50px;margin-right:-250px;">
									<label class="control-label col-md-1" for="coopMode">合作模式<span style="color:red">*</span></label>
									<div class="col-md-2" show-errors>
										<select  class="form-control" id="coopMode" name = "coopMode" ng-model="merhantBaseInfo.coopMode" ng-options="coopMode.name as coopMode.desc for coopMode in CoopModeArray" required>
                                            <option value="">-- 请选择 --</option>
                                         </select>
                                        <div class="help-block" ng-messages="registerForm.coopMode.$error" ng-if="registerForm.coopMode.$touched">
							                <span ng-message="required" >合作模式不能为空</span>
					                	</div>
									</div>
									<label class="control-label col-md-1" for="baseAcctBank">基本帐户开户银行名称</label>
									<div class="col-md-2">
										<input type="text" class="form-control" id="baseAcctBank" name = "baseAcctBank" ng-model="merhantBaseInfo.baseAcctBank" >
									</div>
									<label class="control-label col-md-1" for="baseAcct">银行基本帐户账号</label>
									<div class="col-md-2" >
										<input type="text" class="form-control" id="baseAcct" name ="baseAcct"  ng-model="merhantBaseInfo.baseAcct"  >
									</div>
								</div>
								<div class="form-group" style = "margin-left:50px;margin-right:-250px;">
									<label class="control-label col-md-1" for="org">组织机构代码</label>
									<div class="col-md-2" show-errors>
										<input type="text" class="form-control" id="org" name = "org" ng-model="merhantBaseInfo.org" >
									</div>
									<label class="control-label col-md-1" for="businessLicense">营业执照</label>
									<div class="col-md-2" >
										<input type="text" class="form-control" id="businessLicense" name = "businessLicense" ng-model="merhantBaseInfo.businessLicense" >
									</div>
									<label class="control-label col-md-1" for="taxId">纳税人代码</label>
									<div class="col-md-2" >
										<input type="text" class="form-control" id="taxId" name = "taxId" ng-model="merhantBaseInfo.taxId" >
									</div>
								</div>
								<div class="form-group" style = "margin-left:50px;margin-right:-250px;">
									<label class="control-label col-md-1" for="officePhone">公司电话</label>
									<div class="col-md-2" >
										<input type="text" class="form-control" id="officePhone" name ="officePhone" ng-model="merhantBaseInfo.officePhone" >
									</div>
									<label class="control-label col-md-1" for="address">地址</label>
									<div class="col-md-2" >
										<input type="text" class="form-control" id="address" name = "address" ng-model="merhantBaseInfo.address" >
									</div>
									<label class="control-label col-md-1" for="websiteUrl">公司网址</label>
									<div class="col-md-2" >
										<input type="text" class="form-control" id="websiteUrl" name = "websiteUrl" ng-model="merhantBaseInfo.websiteUrl" >
									</div>
								</div>
								<div class="form-group" style = "margin-left:50px;margin-right:-250px;">
									<label class="control-label col-md-1" for="scale">企业规模</label>
									<div class="col-md-2">
										<select type="text" class="form-control" id="scale" name = "scale" ng-model="merhantBaseInfo.scale" ng-options="scale.name as scale.desc for scale in ScaleArray" >
                                              <option value="">-- 请选择 --</option>
                                        </select>
									</div>
									<label class="control-label col-md-1" for="legalPerson">企业法人</label>
									<div class="col-md-2">
										<input type="text" class="form-control" id="legalPerson" name = "legalPerson" ng-model="merhantBaseInfo.legalPerson" >
									</div>
									<label class="control-label col-md-1" for="legalPersonId">法人证件号码</label>
									<div class="col-md-2">
										<input type="text" class="form-control" id="legalPersonId" name = "legalPersonId" ng-model="merhantBaseInfo.legalPersonId" >
									</div>
								</div>
                                <div class="form-group" style = "margin-left:50px;margin-right:-250px;">
                                   <label class="control-label col-md-1" for="province">合作区域<span style="color:red">*</span></label>
                                   <div class="col-md-2" show-errors>
			                            <select type="text" id = "province" name = "province" class="form-control" ng-model="merhantBaseInfo.province"  ng-change = "changeProvince()" ng-options="province.areaId as province.areaName for province in AllProvinceArray"   required>
			                                <option value="">---请选择---</option>
			                            </select>
								        <div class="help-block" ng-messages="registerForm.province.$error" ng-if="registerForm.province.$touched">
							                <span ng-message="required" >合作区域不能为空</span>
					                    </div>
                                    </div>
                                    <div class="col-md-2">
			                             <select type="text" class="form-control" ng-model="merhantBaseInfo.city" ng-change="changeCity()" ng-options="city.areaId as city.areaName for city  in nowCityArray">
			                                <option value="">---请选择---</option>
			                             </select>
                                    </div>
                                    <div class="col-md-2">
			                             <select type="text" class="form-control" ng-model="merhantBaseInfo.district" ng-change="area=''" ng-options="district.areaId as district.areaName for district  in nowDistrictArray">
			                                 <option value="">---请选择---</option>
			                             </select>
                                    </div>
                                </div>
								<div class="form-group" style = "margin-left:50px;margin-right:-250px;">
									<label class="control-label col-md-1" for="remark">备注</label>
									<div class="col-md-8">
										<textarea class="form-control" cols="4" id="remark" name="remark" ng-model="merhantBaseInfo.remark" rows="2" style = "resize: none;"></textarea>
									</div>
								</div>
							</div>
                       <div>		                 
			      </form>

</div>



about.js:

define(['app'],function(app)
{
	app.controller('AboutViewController',function($scope) {
		document.getElementById("test").onclick = function(){
			swal($scope.title);
        }
	    $scope.title = "About About About About";
        }
    ]);
});
其对应的页面内容about-view.js:
<div ng-controller="AboutViewController">
<button ui-sref="home">Home</button>
<h1>{{ title }}</h1>
<form   name = "registerForm" method="post" class="form-horizontal" novalidate >
                       <p class="bg-warning" style = "margin-left:50px;margin-right:50px;"><i class="glyphicon glyphicon-info-sign"></i><span > <b>温馨提示:带<span style="color:red">*</span>为必填项</b></span><span ng-show = "contractInfo.status == 'INVALID'||contractInfo.status == 'END'" ><b></b></span></p>
                       <p  style = "margin-left:50px;margin-right:50px;" ng-show = "contractInfo.status == 'INVALID'||contractInfo.status == 'END'"><b>已失效或终止的合同不能再修改内容!</b></p>
                       <p  style = "margin-left:50px;margin-right:50px;" ng-show = "contractInfo.status == 'EFFECTIVE'"><b>已生效的合同只能修改部分内容!</b></p>
                       <div>
                               <div class="form-group"  >
                                   <label class="control-label col-md-2 " for = "merchantId">商户<span style="color:red">*</span></label>
									<div class="col-md-3" show-errors>
										 <select  class="form-control" id="merchantId" name = "merchantId" ng-model="contractInfo.merchantId"  ng-options="merchantNameAndId.merchantId as merchantNameAndId.merchantName for merchantNameAndId in merchantNameArray"   required >
                                            <option value="">-- 请选择 --</option>
                                         </select>
                                         <div class="help-block" ng-messages="registerForm.merchantId.$error" ng-if="registerForm.merchantId.$touched">
							                <span ng-message="required" >商户不能为空</span>
					                     </div>
									</div>
									<label class="control-label col-md-2" for="contractNo">合同编号</label>
									<div class="col-md-3" >
										<input  type="text" class="form-control" id="contractNo" name = "contractNo" ng-model="contractInfo.contractNo"  >
									</div>
								</div>
								<div class="form-group" >
									<label class="control-label col-md-2" for="signDate">合同签订日期<span style="color:red">*</span></label>
									<div class="col-md-3" show-errors>
                                        <div class="input-group" readonly= "readonly">
                                           <input type="text" class="form-control" id="signDate" name = "signDate" ng-model="contractInfo.signDate" is-open="signDateOpened" ng-click = "signDateOpened = true" datepicker-options="dateOptions"  current-text="今天"  clear-text="清除" close-text="关闭" readonly ="readonly"   date-format  uib-datepicker-popup required>
                                           <span class="input-group-addon" ng-click = "signDateOpened = true"><i class="glyphicon glyphicon-calendar"></i></span>
                                        </div>
                                        <div class="help-block" ng-messages="registerForm.signDate.$error" ng-if="registerForm.signDate.$touched">
							                <span ng-message="required" >合同签订日期不能为空</span>
					                	</div>
									</div>
									<label class="control-label col-md-2" for="signPerson">合同签署人<span style="color:red">*</span></label>
									<div class="col-md-3" show-errors>
										<input type="text" class="form-control" id="signPerson" name ="signPerson"  ng-model="contractInfo.signPerson"   required >
                                        <div class="help-block" ng-messages="registerForm.signPerson.$error" ng-if="registerForm.signPerson.$touched" >
							                <span ng-message="required" >合同签署人不能为空</span>
					                	</div>
									</div>
								</div>
								<div class="form-group">
									<label class="control-label col-md-2" for="effectDate">合同生效日期<span style="color:red">*</span></label>
									<div class="col-md-3" show-errors>
                                        <div class="input-group" >
										    <input type="text" class="form-control" id="effectDate" name = "effectDate" ng-model="contractInfo.effectDate" is-open="effectDateOpened" ng-click = "effectDateOpened = true" datepicker-options="dateOptions"  current-text="今天"  clear-text="清除" close-text="关闭" readonly ="readonly"   date-format uib-datepicker-popup required>
                                            <span class="input-group-addon" ng-click = "effectDateOpened = true"><i class="glyphicon glyphicon-calendar"></i></span>
                                        </div>
                                        <div class="help-block" ng-messages="registerForm.effectDate.$error" ng-if="registerForm.effectDate.$touched">
							                <span ng-message="required" >合同生效日期不能为空</span>
					                	</div>
									</div>
									<label class="control-label col-md-2" for="expiryDate">合同失效日期<span style="color:red">*</span></label>
									<div class="col-md-3" show-errors>
                                        <div class="input-group" >
										   <input type="text"  class="form-control" id="expiryDate" name = "expiryDate" ng-model="contractInfo.expiryDate"  is-open="expiryDateOpened" ng-click = "expiryDateOpened = true" datepicker-options="dateOptions"  current-text="今天"  clear-text="清除" close-text="关闭" readonly ="readonly"  date-format uib-datepicker-popup required>
                                            <span class="input-group-addon" ng-click = "expiryDateOpened = true"><i class="glyphicon glyphicon-calendar"></i></span>
                                        </div>                                        
                                        <div class="help-block" ng-messages="registerForm.expiryDate.$error" ng-if="registerForm.expiryDate.$touched">
							                <span ng-message="required" >合同失效日期不能为空</span>
					                	</div>
									</div>
								</div>
								<div class="form-group">
									<label class="control-label col-md-2" for="autoResignFlag">到期自动续签<span style="color:red">*</span></label>
									<div class="col-md-3" show-errors>
										 <select  class="form-control" id="autoResignFlag" name = "autoResignFlag" ng-model="contractInfo.autoResignFlag" ng-change = "changeAutoResignFlag()" ng-options="yesNo.name as yesNo.desc for yesNo in YesNoArray"  required >
                                         </select>
                                         <div class="help-block" ng-messages="registerForm.autoResignFlag.$error" ng-if="registerForm.autoResignFlag.$touched">
							                <span ng-message="required" >到期自动续签不能为空</span>
					                     </div>
									</div>
									<label class="control-label col-md-2" for="autoResignYears">自动续签期限</label>
									<div class="col-md-3" >
										<input type="text" class="form-control" id="autoResignYears" name = "autoResignYears" ng-model="contractInfo.autoResignYears" placeholder = "单位为月"   >
                                       <div class="help-block" ng-messages="registerForm.autoResignYears.$error" ng-if="registerForm.autoResignYears.$touched">
							                <span ng-message="required" >自动续签期限不能为空</span>
					                	</div>
									</div>
								</div>
								<div class="form-group">
									<label class="control-label col-md-2" for="fundTyps">涉及款项列表</label>
									<div class="col-md-3" >
										<input type="text" class="form-control" id="fundTyps" name = "fundTyps" ng-model="contractInfo.fundTyps" >
									</div>
									<label class="control-label col-md-2" for="specialInstallReq">有特殊分期要求<span style="color:red">*</span></label>
									<div class="col-md-3"  show-errors>
										<select  class="form-control" id="specialInstallReq" name = "specialInstallReq" ng-model="contractInfo.specialInstallReq"  ng-options="yesNo.name as yesNo.desc for yesNo in YesNoArray"  required>
                                        </select>
                                        <div class="help-block" ng-messages="registerForm.specialInstallReq.$error" ng-if="registerForm.specialInstallReq.$touched">
							                <span ng-message="required" >特殊分期要求不能为空</span>
					                	</div>
									</div>
								</div>
								<div class="form-group">
									<label class="control-label col-md-2" for="remark">备注</label>
									<div class="col-md-8">
										<textarea class="form-control" cols="4" id="remark" name="remark" ng-model="contractInfo.remark" rows="2" style = "resize: none;"></textarea>
									</div>
								</div>
                               <div class="form-group" style = "text-align:center">
                                    <button class="btn btn-primary" type="button" ng-click="okContractEdit()" ng-show = "contractEditable"  >保存修改</button>
                                    <button class="btn btn-warning" type="button" ng-click="cancelContractEdit()"ng-show = "contractEditable" >取消修改</button>
                               </div>
					  </div>
                      <div>                                   
			      </form>
</div>		      

4、效果展示:

首先进入主页


看看其加载的js文件,可以看到只加载 了home.js和home-view.js文件

再点击about按钮,加载about页面,可以看到加载了about.js和about-view.js文件


然后是页面

相关文章

AngularJS 是一个JavaScript 框架。它可通过 注:建议把脚本放在 元素的底部。这会提高网页加载速度,因...
angluarjs中页面初始化的时候会出现语法{{}}在页面中问题,也即是页面闪烁问题。出现这个的原因是:由于...
AngularJS 通过被称为指令的新属性来扩展 HTML。AngularJS 指令AngularJS 指令是扩展的 HTML 属性,带有...
AngularJS 使用表达式把数据绑定到 HTML。AngularJS 表达式AngularJS 表达式写在双大括号内:{{ expres...
ng-repeat 指令可以完美的显示表格。在表格中显示数据 {{ x.Name }} {{ x.Country }} 使用 CSS 样式为了...
$http是 AngularJS 中的一个核心服务,用于读取远程服务器的数据。读取 JSON 文件下是存储在web服务器上...