一、constant
该函数可以将变量注册在模块中,并以服务的形式进行使用。
例如:
var app = angular.module("MyModule",[]).constant("pageConfig",{pageSize:10});
通过以上方式就定义了一个模块中可用的pageConfig的全局变量,我们在模块中可以跟使用服务一样使用该变量,例如:
app.controller("MyController",["$scope","pageConfig",function($scope,pageConfig){
$scope.pageSize = pageConfig.pageSize;
}]);
通过constant定义的变量,一经定义就不能再修改。后面我们会说到功能和其相似的value函数。
二、directive
directive可用于自定义指令,自定义的指令可以用来扩展HTML的功能。例如,我们可以通过directive创建自己的元素标签,在下面的代码中,我们
创建了一个指令lymiPager,该指令用来创建一个实现分页功能的插件。js部分的代码如下:
class="code_img_closed" src="/Upload/Images/2017052505/0015B68B3C38AA5B.gif" alt="">$(function (angular) { angular.module("lymi.pagerModule", []) //分页配置信息 .constant("pagerConfig", { initVisiblePageCount: 4, initCurrentIndex: 1, initPageCount:0 }) .directive("lymiPager",["pagerConfig",function(pagerConfig) { return { link: function (scope, ele, attrs) { //分页插件页码改变时的响应函数 scope.pageChange=function(index) { scope.currentIndex = index; } scope.$watch("currentIndex+pageCount", function () { //定义作用于中分页属性的默认值 if (!attrs.currentIndex) { scope.currentIndex = pagerConfig.initCurrentIndex; } if (!attrs.pageCount) { scope.pageCount = pagerConfig.initPageCount; } if (!attrs.visiblePageCount) { scope.visiblePageCount = pagerConfig.initVisiblePageCount; } //设置显示页码 scope.pagenums = []; var low = 1, high = 1; var showPage = scope.visiblePageCount; if (scope.pageCount > 0) { if (scope.currentIndex - 1 + showPage <= scope.pageCount) { low = scope.currentIndex; high = scope.currentIndex - 1 + showPage; } else { high = scope.pageCount; low = (scope.pageCount - showPage < 0 ? 0 : scope.pageCount - showPage) + 1; } } for (; low <= high; low++) { scope.pagenums.push(low); } //调用外部绑定的函数 scope.onPageChange(); }); }, restrict: "E", scope: { pageCount: "=", currentIndex: "=", visiblePageCount: "@", onPageChange:"&" }, templateUrl: "/html/lymiPager.html" } }]); }(angular));logs_code_collapse">View Code
html代码如下:
<style> .lymiPagination { margin: 0; padding: 0; } .lymiPagination li { border: 1px solid #99bbee; color: #0088dd; list-style: none; margin: 0; padding-left: 10px; padding-right: 10px; float: left; cursor: pointer; } li.active { background-color: #0088ff; color: white; } </style> <ul class="lymiPagination"> <li ng-click="pageChange(1)">首页</li> <li ng-click="pageChange(currentIndex>1?currentIndex-1:1)">上一页</li> <li ng-class="{active:pagenum===currentIndex}" ng-click="pageChange(pagenum)" ng-repeat="pagenum in pagenums">{{pagenum}}</li> <li ng-click="pageChange(currentIndex<pageCount?currentIndex+1:currentIndex)">下一页</li> <li ng-click="pageChange(pageCount)">尾页</li> </ul>View Code
调用指令方式如下所示:
<lymi-pager page-count="totalPages" current-index="pageIndex" visible-page-count="4" class="pager" on-page-change="search(searchKey,pageIndex)"></lymi-pager>