AngularJS学习之 ngTable 翻页 功能以及利用angular service准备测试数据

时间:2021-07-10 08:02:47

1.官网链接  https://github.com/esvit/ng-table#4.0.0

AngularJS学习之 ngTable 翻页 功能以及利用angular service准备测试数据

2.安装ngTable后,一定要记得先注册到自己的项目

.module('pttengApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch',
'mgcrea.ngStrap',
'ngTable'
])

3.编辑使用ngTable的controller  JS文件

angular.module('pttengApp')
.controller('ArticlelistCtrl', function ($scope,$location,ArticleService,NgTableParams) {/*NgTableParams一定要放在正确的位置*/
var self=this;
var simplelist=ArticleService.getAll(); /*这个就是传给NgTableParams的数据,也就是我们table里要显示的各行数据*/
self.tableParams=new NgTableParams({ count: 5},{counts: [5, 10, 20],dataset:simplelist});
self.selectedPageSizes=self.tableParams.settings().counts;
self.availablePageSizes = [5, 10, 15, 20, 25, 30, 40, 50, 100];
self.changePage = changePage; function changePage(nextPage){
self.tableParams.page(nextPage);
}
function changePageSize(newSize){
self.tableParams.count(newSize);
}
function changePageSizes(newSizes){
// ensure that the current page size is one of the options
if (newSizes.indexOf(self.tableParams.count()) === -1) {
newSizes.push(self.tableParams.count());
newSizes.sort();
}
self.tableParams.settings({ counts: newSizes});
}
});

4.html部分的书写

<table ng-table="articlelist.tableParams" show-filter="true" class="table table-hover">/*黑色高亮的就是使用ngTable的controller name*/
<tr ng-repeat="article in $data">/*强调这个$data就是说这个很关键,这个data是tableParams里的data数组,也就是通过dataset添加进去要显示的各行数据*/
<td>{{article.id}}</td>
<td>{{article.name}}</td>
<td>{{article.type}}</td>
<td>{{article.createtime}}</td>
<td>{{article.lastmodifiedtime}}</td>
</tr>
</table>

*************************

利用 yo angular:service Article-Service创建一个服务,生成的js文件里面可以创建一个构造函数,属性是JSON数据,方法就用来返回这些数据,然后我们就可以利用这个服务提供的数据进行前端功能的测试啦(在需要用到他的controller里面注人这个service,比如

.controller('ArticlelistCtrl', function ($scope,$location,ArticleService,NgTableParams) {

'use strict';

/**
* @ngdoc service
* @name pttengApp.ArticleService
* @description
* # ArticleService
* Service in the pttengApp.
*/
angular.module('pttengApp')
.service('ArticleService', function () {
// AngularJS will instantiate a singleton by calling "new" on this function
var articles = [
{
"id": "1",
"name": "行业动态",
"type": "行业",
"createtime": "2017-05-06",
"lastmodifiedtime": "2017-05-06",
"createuser": "admin",
"status": "0",
"operation": "delete"
},
{
"id": "2",
"name": "JSON",
"type": "语法",
"createtime": "2017-05-06",
"lastmodifiedtime": "2017-05-06",
"createuser": "admin",
"status": "0",
"operation": "delete"
}
]; return {
getAll: function () {
return articles;
},
getById: function () {
for (var i = 0; i < articles.length; i++) {
if (articles[i].id === id) {
return articles[i];
}
}
return null;
}
}; });