我正在使用Angular Material的md-virtual-repeat指令进行无限滚动,我需要用$http请求替换它的
demo $timeout函数.但我无法找到正确的解决方案.
在下面的代码中,无限滚动工作正常,但不显示来自http请求的数据.问题是我不知道将$http结果绑定到infiniteItems的方法.
在下面的代码中,无限滚动工作正常,但不显示来自http请求的数据.问题是我不知道将$http结果绑定到infiniteItems的方法.
Here是plunker.
的index.html
<body ng-app="infiniteScrolling" class="virtualRepeatdemoInfiniteScroll">
<div ng-controller="AppCtrl as ctrl" ng-cloak>
<md-content layout="column">
<md-virtual-repeat-container id="vertical-container" flex>
<div md-virtual-repeat="item in ctrl.infiniteItems" md-on-demand
class="repeated-item" flex>
{{item.id}}
</div>
</md-virtual-repeat-container>
</md-content>
</div>
</body>
JS:
(function () {
'use strict';
angular
.module('infiniteScrolling',['ngMaterial'])
.controller('AppCtrl',function ($timeout,$scope,$http) {
this.infiniteItems = {
numloaded_: 0,toLoad_: 0,items:[],getItemAtIndex: function (index) {
if (index > this.numloaded_) {
this.fetchMoreItems_(index);
return null;
}
return index;
},getLength: function () {
return this.numloaded_ + 5;
},fetchMoreItems_: function (index) {
if (this.toLoad_ < index) {
this.toLoad_ += 20;
$http.get('items.json').success(function (data) {
var items = data;
for (var i = 0; i < items.length; i++) {
this.items.push(items[i].data);
}
this.numloaded_ = this.toLoad_;
}.bind(this));
}
}
};
});
})();
解决方法
这个工作:
plnkr
> getItemAtIndex返回索引而不是项目
>如果你检查过你所推动的东西,你会看到我的插件中的第33行,我的结论是obj.data,而不是简单的obj
(function () {
'use strict';
angular.module('infiniteScrolling',['ngMaterial'])
.controller('AppCtrl',function ($scope,$http) {
// 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,items: [],// required.
getItemAtIndex: function (index) {
if (index > this.numloaded_) {
this.fetchMoreItems_(index);
return null;
}
return this.items[index];
},// required.
getLength: function () {
return this.numloaded_ + 5;
},fetchMoreItems_: function (index) {
if (this.toLoad_ < index) {
this.toLoad_ += 5;
$http.get('items.json').then(angular.bind(this,function (obj) {
this.items = this.items.concat(obj.data);
this.numloaded_ = this.toLoad_;
}));
}
}
}
})
})();