这是场景:
我正在使用带有Angular JS和Boostrap UI的ASP.NET MVC站点.我有一个动态ul列表,由通过控制器调用AngularJS提供的数据填充,通过输入搜索框过滤该列表.该列表还通过分页(UI Bootstrap控件)进行控制,我已设置为每页显示10个结果,列出100个左右的项目.当用户在搜索框中键入时,此列表会被过滤,但我希望更新分页,因此请考虑以下示例:
该列表有10页项目(100项),用户在输入搜索框中键入一些文本,将列表过滤到20个左右的项目,因此分页应从10页更新为2页.
我认为必须在某个地方设置一个$watch设置,可能在列表项目被过滤后再更新分页页数,但是我对AngularJS很新,所以有人可以向我解释如何做到这一点吗?
非常感谢.我在下面发布了我的代码:
<div data-ng-app="dealsPage"> <input type="text" data-ng-model="cityName" /> <div data-ng-controller="DestinationController"> <ul> <li data-ng-repeat="deals in destinations | filter: cityName | startFrom:currentPage*pageSize | limitTo:pageSize">{{deals.Location}}</li> </ul> <br /> <pagination rotate="true" num-pages="noOfPages" current-page="currentPage" max-size="maxSize" class="pagination-small" boundary-links="true"></pagination> </div>
var destApp = angular.module('dealsPage',['ui.bootstrap','uiSlider']); destApp.controller('DestinationController',function ($scope,$http) { $scope.destinations = {}; $scope.currentPage = 1; $scope.pageSize = 10; $http.get('/Deals/GetDeals').success(function (data) { $scope.destinations = data; $scope.noOfPages = data.length / 10; $scope.maxSize = 5; }); }); destApp.filter('startFrom',function () { return function (input,start) { start = +start; //parse to int return input.slice(start); }; });
解决方法
因为您的分页是链接过滤器的组合,所以Angular不知道当cityName更改时,它应该将currentPage重置为1.您需要使用自己的$watch自己处理.
您还需要将startFrom过滤器调整为(currentPage – 1)* pageSize,否则,始终从第2页开始.
一旦你开始这样做,你会发现你的分页不准确,因为它仍然基于destination.length,而不是过滤的目的地子集.为此,您需要将过滤逻辑从视图移动到控制器,如下所示:
HTML
<div data-ng-app="dealsPage"> <input type="text" data-ng-model="cityName" /> <div data-ng-controller="DestinationController"> <ul> <li data-ng-repeat="deals in filteredDestinations | startFrom:(currentPage - 1)*pageSize | limitTo:pageSize">{{deals.Location}}</li> </ul> <br /> <pagination rotate="true" num-pages="noOfPages" current-page="currentPage" max-size="maxSize" class="pagination-small" boundary-links="true"></pagination> </div>
JavaScript的
var destApp = angular.module('dealsPage',['ui.bootstrap']); destApp.controller('DestinationController',$http,$filter) { $scope.destinations = []; $scope.filteredDestinations = []; for (var i = 0; i < 1000; i += 1) { $scope.destinations.push({ Location: 'city ' + (i + 1) }); } $scope.pageSize = 10; $scope.maxSize = 5; $scope.$watch('cityName',function (newCityName) { $scope.currentPage = 1; $scope.filteredDestinations = $filter('filter')($scope.destinations,$scope.cityName); $scope.noOfPages = $scope.filteredDestinations.length / 10; }); }); destApp.filter('startFrom',start) { start = +start; //parse to int return input.slice(start); }; });