无限滚动问题

时间:2015-08-28 10:12:06

标签: angularjs scroll angularjs-directive angularjs-scope browserify

我发现无限滚动的example并尝试执行相同的操作,但在修复所有错误后我发现它仍然无法正常工作。

这是指令:

module.exports = /*@ngInject*/
function scrollDirective($rootScope) {
    return {
        link: function (scope, elm, attr) {
            var raw = elm[0];

            elm.bind('expressly', function() {
            if (raw.scrollTop + raw.offsetHeight >= raw.scrollHeight) {
                scope.$apply(attr.scrollDirective); 
            }
        });
        }
    };
};

然后它在控制器中如何发生(我有承诺中的JSON数据)

module.exports = /*@ngInject*/
function cardController($scope, dataFactory) {
  var promise = dataFactory.get();
  promise.then(function(data) {
    $scope.data = data;
    $scope.items = [];
    //$scope.items.push($scope.data[0]);
    var counter = 0;

    $scope.loadMore = function() {
      for (var i = counter; i < counter+9; i++) {
          $scope.items.push($scope.data[i]);
      }
      counter += 9;
    };

    $scope.loadMore();
    }, function(reason) {
      console.log('Failed: ' + reason);
    });
};

最后是html:

<div class="mdl-grid" scroll-directive="loadMore()"> 
  <div class="mdl-cell mdl-cell--4-col mdl-cell--4-col-phone" ng-repeat="item in items">
    <md-card>
      <img ng-src="{{ item.url }}" class="md-card-image">
      <md-card-content>
        <md-icon ><i class="material-icons md-36 md-album">photo_album</i></md-icon>
        <h3 class="md-title">{{ item.title }}</h3>
      </md-card-content>
    </md-card>
  </div>
</div>

1 个答案:

答案 0 :(得分:1)

实际上它很简单。在指令而不是elm中,我使用$document并将参数i传递给函数。在探索i的内容后,我通过i.target.activeElement找到了我需要的所有参数。这是解决方案:

function scrollDirective($rootScope,$document) {
    return {
        link: function (scope, elm, attr) {
            var raw = elm[0];

            $document.bind('scroll', function (i) {
                if (i.target.activeElement.scrollTop+i.target.activeElement.offsetHeight +5>= i.target.activeElement.scrollHeight){
                    scope.$apply(attr.scrollDirective); 
                }
            });
        }
    };
};