在 AngularJS 材质中使用 md-virtual-repeat 的无限滚动



我正在尝试实现无限滚动,如下所述:https://material.angularjs.org/latest/demo/virtualRepeat

但是,我找到的所有示例都使用 $http.get 来请求外部 .json 文档。我想使用存储在控制器内另一个函数检索的范围内的现有 JSON 数组。为了简化测试目的,我创建了一个仅执行基础知识的 plunkr。

这是我使用外部.json文件找到的一个工作示例:http://plnkr.co/edit/e32qVQ4ECZBleWq2Gb2O?p=preview

我需要做的就是用我的 $scope.items 替换 $http.get 请求代码,但我的尝试没有成功。这是我一直在处理的修改示例:http://plnkr.co/edit/S2k6pxJ2mZ7MQsILnmvS?p=preview

(function () {
'use strict';
angular
  .module('infiniteScrolling', ['ngMaterial'])
  .controller('AppCtrl', function ($timeout,$scope) {
      $scope.items = [
{
"categoryId": "cat1",
"id": "pack0"
},
{
"categoryId": "cat1",
"id": "pack8"
},
{
"categoryId": "cat1",
"id": "pack9"
},
{
"categoryId": "cat1",
"id": "pack10"
},
{
"categoryId": "cat1",
"id": "pack11"
}
];

      // In this example, we set up our model using a plain object.
      // Using a class works too. All that matters is that we implement
      // getItemAtIndex and getLength.
       var vm = this;
      vm.infiniteItems = {
          numLoaded_: 0,
          toLoad_: 0,
          // Required.
          getItemAtIndex: function (index) {
              if (index > this.numLoaded_) {
                  this.fetchMoreItems_();
                  return null;
              }
              return this.items[index];
          },
          // Required.
          getLength: function () {
              return this.numLoaded_ + 5;
          },
          fetchMoreItems_: function ($scope, index) {
              if (this.toLoad_ < index) {
                  this.toLoad_ += 5;
                  $scope.items.then(angular.bind(this, function (obj) {
                      this.items = this.items.concat(obj.data);
                      this.numLoaded_ = this.toLoad_;
                  }));                  
                  }
          }
      };
   });
})();

http://plnkr.co/edit/GUvhluPx3bS2XUSjFHvN?p=preview

由于您正在尝试替换返回承诺的$http.get调用,因此您可以将其替换为$timeout(因为这也会返回承诺并将触发$apply(。 唯一的警告是$timeout返回的对象没有数据属性(这只是 httppromise 的一个功能,因为它具有 http 状态等(,所以我还必须obj.data更改为 obj

最新更新