【问题标题】:Infinite Scrolling using md-virtual-repeat in AngularJS Material在 AngularJS Material 中使用 md-virtual-repeat 进行无限滚动
【发布时间】:2018-01-13 13:21:36
【问题描述】:

我正在尝试实现此处记录的无限滚动: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_;
                  }));                  

                  }
          }
      };

   });
})();

【问题讨论】:

  • 非常好的问题,但你不能只是放入一个数组来代替一个承诺的东西,在这里解决一个解决方案......想知道你是否坚持这个版本的角度材料还是我/你应该考虑用更新的版本来解决这个问题。

标签: javascript angularjs angularjs-material


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2017-02-08
    • 2018-08-24
    • 1970-01-01
    • 1970-01-01
    • 2017-05-26
    • 2018-05-09
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    相关资源
    最近更新 更多