Javascript 当图像不可用时,加载图像或显示字母
我试图测试图像是否存在,或者显示字母代替图像,但无法使其工作Javascript 当图像不可用时,加载图像或显示字母,javascript,angularjs,Javascript,Angularjs,我试图测试图像是否存在,或者显示字母代替图像,但无法使其工作 app.controller('task1Controller',['$scope', 'taskFactory', '$state', 'imageTestService', function($scope, taskFactory, $state, imageTestService){ $scope.taskData = {}; $scope.current = 0; taskFactory.get()
app.controller('task1Controller',['$scope', 'taskFactory', '$state', 'imageTestService', function($scope, taskFactory, $state, imageTestService){
$scope.taskData = {};
$scope.current = 0;
taskFactory.get().then(function(response){
$scope.jsonData = response.data.resultCareGivers;
});
$scope.IsValidImageUrl = function(url){
imageTestService.IsValidImageUrl(url);
};
$scope.back = function(){
$scope.current = ($scope.current !== 0 ? $scope.current - 1 : 0);
};
$scope.next = function(){
$scope.current = ($scope.current !== $scope.jsonData.length-1 ? $scope.current + 1 : $scope.jsonData.length-1);
};
}]);
测试图像的服务:
app.service('imageTestService', function(){
this.IsValidImageUrl = function(url){
var img = new Image();
img.onerror = function() { return false; };
img.onload = function() { return true; };
img.src = url;
};
});
Html:
如何解决此问题?您需要返回值
$scope.IsValidImageUrl = function(url){
return imageTestService.IsValidImageUrl(url);
};
您需要返回值
$scope.IsValidImageUrl = function(url){
return imageTestService.IsValidImageUrl(url);
};
代码中有两个问题 首先,您没有将任何内容返回到视图中,还需要检查服务是否返回任何内容
$scope.IsValidImageUrl = function(url){
return imageTestService.IsValidImageUrl(url);
};
其次,您正在使用ng model
绑定图像。相反,您必须使用ng src
<div ng-if=IsValidImageUrl(jsonData[current].profilepic)>
<img ng-src="{{jsonData[current].profilepic}}"/>
</div>
您的代码中有两个问题 首先,您没有将任何内容返回到视图中,还需要检查服务是否返回任何内容
$scope.IsValidImageUrl = function(url){
return imageTestService.IsValidImageUrl(url);
};
其次,您正在使用ng model
绑定图像。相反,您必须使用ng src
<div ng-if=IsValidImageUrl(jsonData[current].profilepic)>
<img ng-src="{{jsonData[current].profilepic}}"/>
</div>
更新了代码,我仍然收到图像的加载资源失败错误
。json包含http://via.placeholder.com/350x150
哪个是有效的图像urljsonData[current]。profilepic包含哪些内容?或者它是其他属性?它是一个图像URL尝试在视图上打印{{jsonData[current].profilepic}},并检查值是否正确?是的,当我打印时它正确出现。它打印http://via.placeholder.com/350x150
但是图像没有加载到代码中,我仍然得到图像的加载资源失败错误。json包含http://via.placeholder.com/350x150
哪个是有效的图像urljsonData[current]。profilepic包含哪些内容?或者它是其他属性?它是一个图像URL尝试在视图上打印{{jsonData[current].profilepic}},并检查值是否正确?是的,当我打印时它正确出现。它打印http://via.placeholder.com/350x150
但图像不会加载到ng src中