所以我编写了一个简单的指令,当第一个图像无法加载时,它会截取404图像并回退到另一个图像。
效果很好,但我在某些网址上遇到问题,这些网址会返回404状态代码,但仍会在正文中返回图片(例如Google+)。
如果您想查看代码示例,请访问https://jsfiddle.net/4cjb5srh/1/
angular.module('test', [])
.directive('imgMissing', [function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('error', function() {
console.log('image missing');
});
}
}
}]);
在此示例中,Google+图片不会触发错误,但是图片会触发错误。我尝试使用jquery .error()而不是jqlite bind('错误')但没有解决问题。
编辑:JimTheDev指出它可能与if a ngSrc path resolves to a 404, is there a way to fallback to a default?的问题相同。我和其他问题都要回到404,但是这个问题特定于返回404但是没有触发错误的情况(当响应类型被指定时,kwan245如下所述) )。
答案 0 :(得分:0)
如果响应以图像作为响应类型来实现,则看起来404被忽略。
不幸的是,因为这是使用浏览器本机img src,我认为我们不能在javascript中拦截。
另一种方法是自己做$ http并删除img src
angular.module('test', [])
.directive('imgMissing', function($http) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
$http.jsonp(attrs.srcurl +"?callback=JSON_CALLBACK").success(function(res){
element.src('data:image/jpeg;base64,' + res.data);
}).error(function (res) {
console.log("failed");
});
}
}});
在html中: