在项目中许多页面都用到了分页,然后每个页面都有许多重复的分页代码,于是自己写了一份简易的分页指令,简化页面的代码,且容易维护,写在博客中当做备份,方便以后查阅。 以下是定义指令及其应用的步骤:
1.指令定义
定义一个js文件,page-directive.js,用来写分页的指令代码,这个文件中包含了分页的模板,以下是js文件中的所有代码:<div class="jb51code">
<pre class="brush:js;">
'use strict';
(function () {
angular.module('template/pageInit/pageInit.html',[]).run([
'$templateCache',function($templateCache) {
$templateCache.put('template/pageInit/pageInit.html','<ul class="pagination-main">\n'+
' <li class="prev-page" ng-class="{disabled:pageData.currentPage==1}" title="首页">\n'+
' <a href="javascript:void(0);" ng-click="on_loadPage(1)"><span class="fa fa-fast-backward">\n'+
' \n'+
' <li class="prev-page" ng-class="{disabled:pageData.currentPage==1 }">\n'+
' <a href="javascript:void(0);" ng-click="on_prev()" title="上一页"><span class="fa fa-step-backward">\n'+
' \n'+
' <li class="data-page" ng-repeat="page in pageData.pages" ng-class="{\'first-page\': page==1,\'last-page\': page==pageData.totalPage}">\n'+
' <a ng-if="page!=\'...\'" href="javascript:void(0);" ng-class="{\'bg-custom\': page==pageData.currentPage}" ng-click="on_loadPage(page,tabData)">{{ page }}\n'+
' <a ng-if="page==\'...\'" href="javascript:void(0);" ng-class="{\'bg-custom\': page==pageData.currentPage}" ng-click="">{{ page }}\n'+
' \n'+
' <li class="next-page" ng-class="{disabled:pageData.currentPage==pageData.totalPage}">\n'+
' <a href="javascript:void(0);" ng-click="on_next()" title="下一页"><span class="fa fa-step-forward">\n'+
' \n'+
' <li class="skip-page">
' <input type="button" value="跳转" ng-click="on_loadPage(inpage)">
' \n'+
' <li class="data-num"><a class="cursor-text" href="#">共{{pageData.count}}条\n'+
'\n'+
''
);
}
]);
angular.module('pageInit',['template/pageInit/pageInit.html'])
.directive('pageInit',['pageinitTemplate',function(pageinitTemplate) {
return {
restrict : 'AE',templateUrl: function (tElement,tAttrs) {
return tAttrs.templateUrl || pageinitTemplate.getPath();
},replace : true,scope : {
pageData : '=',prev : '&',next : '&',loadPage : '&'
},link : function(scope,element,attrs) {
scope.on_prev = function() {
if(scope.prev) {
scope.prev();
}
};
scope.on_next = function() {
if(scope.next) {
scope.next();
}
};
scope.on_loadPage = function(page) {
scope.inpage = undefined;
if(scope.loadPage) {
scope.loadPage({page: page});
}
};
}
};
}])
.provider('pageinitTemplate',function () {
var templatePath = 'template/pageInit/pageInit.html';
this.setPath = function (path) {
templatePath = path;
};
this.$get = function () {
return {
getPath: function () {
return templatePath;
}
};
};
});
}).call(window);