angularJs 前端的页面分解与组装
- - Web前端 - ITeye博客将分解的页面写成directive. 事实上,还可以更进一步,将templateUrl写成可传入的参数. 但是那样的话就跟下面这个方法差不多了. 使用ng-include非常简单. 请注意src的参数是表达式,如果要传静态的字符串参数,请用引号将参数包裹起来. 对ng-include稍作处理,可以实现更复杂的功能.
实现前端页面的复用
将分解的页面写成directive. 例如下面这个样子:
angular.module('pageComponents', [], function($compileProvider){
$compileProvider.directive('commonHeader', function($compile) {
return {
templateUrl: 'templete/common/common_header.html',
replace: true,
transclude: false,
restrict: 'A',
scope: false
};
});
$compileProvider.directive('commonFooter', function($compile) {
return {
templateUrl: 'templete/common/common_footer.html',
replace: true,
transclude: false,
restrict: 'A',
scope: false
};
});
});
事实上,还可以更进一步,将templateUrl写成可传入的参数。但是那样的话就跟下面这个方法差不多了。
使用ng-include非常简单。请注意src的参数是表达式,如果要传静态的字符串参数,请用引号将参数包裹起来。就像下面这个例子。
<!-- header -->
<ng-include src="'common_header.html'"></ng-include>
<div class="container">
<!-- angular ng-view -->
<div ng-view></div>
<!-- /angular ng-view -->
</div>
<!-- Footer -->
<ng-include src="'common_footer.html'"></ng-include>
对ng-include稍作处理,可以实现更复杂的功能。例如下面这个动态加载表单页面的例子,就是通过变换ng-include的src参数实现的。
$compileProvider.directive("dynamicFormInput", ['$http', '$templateCache',
function($http, $templateCache) {
return {
restrict : 'E',
scope : {
model : '=',
section : '='
},
template : '<ng:include src="tpl"></ng:include>',
link : function(scope, iElement, iAttrs) {
switch(scope.section.sectionTypeId) {
case 1:
$http.get('partials/survey/textInput.html', {
cache : $templateCache
});
scope.tpl = "partials/survey/textInput.html";
break;
case 2:
$http.get('partials/survey/selectOneOption.html', {
cache : $templateCache
});
scope.tpl = "partials/survey/selectOneOption.html";
break;
case 6:
if (scope.section.sectionId == 19) {
$http.get('partials/survey/addressSelection.html', {
cache : $templateCache
});
scope.tpl = "partials/survey/addressSelection.html";
}
break;
}
}
}
}]);
最后必须说明的是,这三种方法实质上都是利用ajax来加载模板。使用ajax来实现页面分解这样的功能,相比传统的使用后台动态脚本语言的方案,必然会 带来额外的开销。事实上,不光angularjs是这样,我所接触过的所有前端框架都是如此。这是浏览器端的宿命。这里所造成的负载和与后台动态脚本语言之间的优劣,只能由技术主管自己权衡。