關於angularjs的學習過程,我剛創建了一個帶分頁的表格。下面是代碼angularjs ng-repeat with filter返回空數組第二次
HTML
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>EMAIL</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in data | range:selectedPage:pageSize">
<td>{{user.id}}</td>
<td>{{user.name}}</td>
<td>{{user.email}}</td>
</tr>
</tbody>
</table>
<div class="pull-right btn-group">
<a ng-repeat="page in data | filter:pageCount:pageSize" ng-click="selectPage($index + 1)" class="btn btn-default" ng-class="getPageClass($index + 1)">
{{$index + 1}}
</a>
</div>
</div>
JS
var exampleTable = angular.module('exampleTable', []);
exampleTable.controller('exampleTableCont', function($scope) {
$scope.data = [{
"id": 1,
"name": "john",
"email": "[email protected]"
}, {
"id": 3,
"name": "william",
"email": "[email protected]"
}, {
"id": 2,
"name": "clark",
"email": "[email protected]"
}, {
"id": 5,
"name": "Brian",
"email": "[email protected]"
}, {
"id": 4,
"name": "smith",
"email": "[email protected]"
}, {
"id": 6,
"name": "chris",
"email": "[email protected]"
}, {
"id": 7,
"name": "june",
"email": "[email protected]"
}];
$scope.selectedPage = 1;
$scope.pageSize = 3;
$scope.selectPage = function(newPage) {
$scope.selectedPage = newPage;
}
$scope.getPageClass = function(page) {
return $scope.selectedPage == page ? "btn-primary" : "";
}
});
exampleTable.filter("pageCount", function() {
return function(data, size) {
if (angular.isArray(data)) {
var result = [];
for (var i = 0; i < Math.ceil(data.length/size); i++) {
result.push(i);
}
console.log(result);
return result;
} else {
return data;
}
}
});
exampleTable.filter("range", function($filter) {
return function(data, page, size) {
if (angular.isArray(data) && angular.isNumber(page) && angular.isNumber(size)) {
var start_index = (page - 1) * size;
if (data.length < start_index) {
return [];
} else {
console.log($filter("limitTo")(data.splice(start_index), size));
return $filter("limitTo")(data.splice(start_index), size);
}
} else {
return data;
}
}
});
這裏是plunker
我試圖安慰range
過濾器,而這樣做我看到它運行兩次。 第一次用3行數據,第二次用空數組。由於它沒有繪製返回空數組表。
我可以知道爲什麼它會返回空數組而不是3數組。如何克服這一點?
pageCount
過濾器也不像預期的那樣工作,但這裏的pageCount
過濾器甚至沒有運行一次。
感謝您的幫助。但是數據被管道 – rram
自動發送到過濾器,以便使用多個數據過濾器,您必須使用如下語法 {{yourExpression | yourFilter:arg1:arg2:...}} –
檢查這個雖然..它會幫助你http://jsfiddle.net/4PYZa/282/ –