1

我有一个$scope包含 50 多条记录的对象。我有一个通过limitTo<div>显示前5条记录。$scope

我有一个“查看更多”按钮,每次点击都会显示接下来的 5 条记录。

但是,一旦显示了 50 条记录,我希望我的按钮调用一个函数getMore(),就其本身而言,它会获得另外 50 条记录。

HTML:

<div ng-repeat="data in myData | limitTo: Limit" >
    {{ data.name }}
</div>


<button ng-click="Limit = Limit + 5">
    See More
</button>

<button ng-click="getMore()">
    See More
</button>

JS:

app.controller("MyCtrl", function($scope) {

    $scope.Limit = 5;

    $scope.getMore = function () {
        // Call service to get more data
    };

});

我怎样才能消除需要有 2 个按钮?而且,getMore()如果再次返回最多 50 个结果(或 34 个),一次显示 5 个?

谢谢

4

1 回答 1

1

You're trying to implement infinite scrolling.

Here's my simple solution which implies pagination support on the back-end:

Coffeescript:

angular.module('yourApp.controllers').controller 'InfiniteCtrl',
 ['$resource', '$scope', 'DataResource',
  ($resource, $scope, DataResource) ->
    new class InfiniteCtrl
      constructor: () ->
        $scope.myData = []
        @counter = 0
        @loadMore()

      loadMore: () ->
        @counter += 1
        @DataResource.get({page:@counter}).$promise.then (data) ->
          $scope.myData = $scope.jobs.concat(data)
  ]

Compiled JS:

angular.module('yourApp.controllers').controller('InfiniteCtrl', [
  '$resource', '$scope', 'DataResource', function($resource, $scope, DataResource) {
    var InfiniteCtrl;
    return new (InfiniteCtrl = (function() {
      function InfiniteCtrl() {
        $scope.myData = [];
        this.counter = 0;
        this.loadMore();
      }

      InfiniteCtrl.prototype.loadMore = function() {
        this.counter += 1;
        return this.DataResource.get({
          page: this.counter
        }).$promise.then(function(data) {
          return $scope.myData = $scope.jobs.concat(data);
        });
      };

      return InfiniteCtrl;

    })());
  }
]);

You can adapt this solution to limit the amount of items you show.

In your template, showing more data can be done with :

<button ng-click="ctrl.loadMore()">More!</button>
于 2014-07-17T09:31:43.837 回答