我想为我的传入数据延迟加载图片,障碍是我必须与照片一起显示数据
方案: 随着我的数据我收到一个Id,我必须调用一个函数,从请求的UR获取图像和图像格式是base64
测试1个案例
*请注意,它只是一个动态的示例数据
<div ng-repeat="data in Data">
<div class="col-md-2">
<img ng-src="data:image/jpeg;base64,{{data.photo}}" ng-init="callBackendImage(data.id)">
<!--I want to call this function everytime to get image-->
<!--reponse if image is {name:'xyz',image:'base64string'-->
</div>
<div class="col-md-10">
<td style="vertical-align: top;min-width: 35px;">
<span><b>{{data.location}}</b></span>
</td>
</div>
</div>
app.js
$scope.callBackendImage= function (id, data) {
console.log('caled')
console.log(id)
$rootScope.showPreloader = true;
awtcDataService.getRequest(id).then(function (_response) {
console.log(_response)
var res = _response
if(res.data.success) {
data.photo = res.data.image//getting base64 string }
console.log(data)
// else {
// ctrl.errorCallBack = true
// ctrl.errorFunction = 3
// }
$rootScope.showPreloader = false;
})
上述代码存在问题:
该函数被调用,如果数据太长,我得到我的图像会有很多请求后端,我想只在它在视口或容器中可用时用id调用这个函数换句话说在滚动上使用id callBackendImage(data)
调用此函数任何帮助都会得到很大的帮助
答案 0 :(得分:0)
您可以订阅windows.onscroll
活动。如果屏幕上显示特定data in Data
(x.offsetTop <= window.scrollY + window.innerHeight
),则应调用callBackendImage
并调用后续awtcDataService.getRequest
,否则data.photo
不应加载且可见(<img ng-show='data.photo' ng-src="data:image/jpeg;base64,{{data.photo}}" />
):
angular.module('app', []).controller('ctrl', function($scope, $timeout) {
$scope.Data = [];
$scope.loaded = 0;
for (var i = 0; i < 150; i++)
$scope.Data[i] = {
name: 'Name' + i
};
//just stub
$scope.callBackendImage = function(id){
$timeout(function() {
$scope.Data[id].photo = id;
$scope.loaded++;
}, 1000 + 2000 * Math.random());
}
function ProcessVisible() {
var elements = Array.from(document.getElementsByClassName('photos'));
var visible = elements.filter(function(x) {
return x.offsetTop < window.scrollY + window.innerHeight;
})
for (var item of visible){
var temp = $scope.Data[item.id];
if (!temp.loading){
temp.loading = true;
$scope.callBackendImage(item.id)
}
}
}
window.onscroll = ProcessVisible;
$timeout(ProcessVisible, 100);
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='app' ng-controller='ctrl' id='root'>
Loaded {{loaded}} of {{Data.length}}
<ul>
<li class='photos' ng-style='{"background-color": data.photo ? "#acffac": "white"}' ng-repeat='data in Data' id='{{$index}}'>{{data.name}}: {{data.photo}}</li>
<ul>
<div>
&#13;