javascript - 在 AngularJS Material 中使用 md-virtual-repeat 进行无限滚动

标签 javascript angularjs angularjs-material

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

但是,我发现的所有示例都使用 $http.get 来请求外部 .json 文档。我想使用存储在 Controller 内另一个函数检索的范围中的现有 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

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

关于javascript - 在 AngularJS Material 中使用 md-virtual-repeat 进行无限滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48235666/

相关文章:

javascript - 如何访问 DIV 的 innerHTML onclick(ng-click)Angular JS 中的按钮

javascript - 在 mdDialog 中创建可编辑数据为 json 的表

javascript - 在类上滚动时更改导航

javascript - 为什么当用户点击太快时 jQuery Mobile Simple Dialogue 会卡住?

javascript - Angular - 如何在 $compile 中使用 $scope?

angularjs - 使用 Angular-formly 时动态添加指令

css - 如何使用 Angular/Material2 运行混合应用程序 AngularJS/Material1

angularjs - 表 tr 重复中的 Angular Material md-radio-button

javascript - 带正方形的特殊布局 div 正方形

javascript - 加载页面预加载器时隐藏滚动条