为了在图像不存在时显示默认图像(而不是损坏的图像),我使用以下代码:
<img ng-show="order.img" ng-src="{{order.img | fPath}}" onerror="this.style.display='none';"/>
<img ng-hide="order.img" ng-src="{{'default.png' | imgPath}}" />
这里,fPath
、imgPath
是将前缀附加到图像名称的过滤器。
大多数情况下,它工作得很好(图像会被渲染)。但是,在某些情况下,图像不会显示。在这种情况下,有角度的片段会被翻译成这个html(注意第一个img标签中的style="display: none;"
):
<img ng-show="order.img" ng-src="http://xx.s3.amazonaws.com/o/img1.jpg" onerror="this.style.display='none'" src="http://xx.s3.amazonaws.com/o/img1.jpg" style="display: none;">
<img ng-hide="order.img" ng-src="http://xx.s3.amazonaws.com/default.png" class="ng-hide" src="http://xx.s3.amazonaws.com/default.png" style="">
问题:这可能是什么原因?以及可能的解决方案?是不是onerror
比预期的更早被触发?
PS:http://xx.s3.amazonaws.com/o/img1.jpg
是一个有效的图像路径,并且是可用的。
更新:这就是应用程序/路线/控制器的定义
路线
t_app.config(function ($stateProvider, $urlRouterProvider, $httpProvider) {
// ...
$stateProvider.state('ref', {
url: '/orders/:ref',
templateUrl: 'views/order.htm',
controller: 'orderController'
});
// ...
});
控制器
t_app.controller('orderController', ['$scope', '$stateParams', function($scope, $stateParams) {
// Load the order (this step takes a while)
}]);
我认为发生在您身上的事情是:http://plnkr.co/edit/8JL0Op?p=preview
angular.module('app.helper', [])
.controller('ImgController', ['$scope', '$timeout', function($scope, $timeout) {
$scope.img = "";
$timeout(function(){
$scope.img = "9c5595db-db21-4783-902a-8e80b84ae22c/6b89ed2b-878a-4f76-95c4-76ee95f47d9a.jpg";
}, 1500);
}]);
filter.$inject = ["$filter"];
angular.module('app.helper').filter('addPath', filter);
function filter($filter) {
function filterFn(input) {
return "http://cdn.playbuzz.com/cdn/"+input;
}
return filterFn;
}
过滤器在设置order.img
之前添加前缀,因此img src将仅作为前缀(直到加载订单为止),而没有图像名称,从而导致错误的src。我想,但我不能100%确定,原因是$scope.order
在错误触发之前(可能是在缓存结果时)加载,在错误触发之后加载
当您混合使用原生javascript和角度时,很难确定执行顺序
您可以通过在过滤器中添加一个检查来避免这种情况:如果传递给过滤器的值为null、未定义或空字符串,则在这种情况下返回null。像这样的
return typeof input === "undefined" || input === null || input === "" ? null : "http://cdn.playbuzz.com/cdn/"+input;