//添加背景图片
app.directive('setGround', function() {
return {
restrict:'AE',//定义范围
transclude: false,
replace: true,
scope: {
ground: "@", // ground 值传递 (字符串,单向绑定)
},
link:function(scope, element, attrs){
//错误图片和加载图片
var errImg = 'img/404/404.png';
var loadingImg = 'img/loading/loading3.gif';
//监听属性值的变化,为空会进一次 有值又会进一次
attrs.$observe('ground', function (value) {
var backGroundImg = element[0];
if(value){
//用来判断两秒后 图片地址是否还是空的
scope.value = value;
//有值先当有效地址处理,保证图片快速显示
setBackgrund(backGroundImg,value);
/*判断图片地址是否有效,无效一秒后换成404图片*/
var img=new Image();
img.src=value;
setTimeout(function(){
if(img.fileSize > 0 || (img.width > 0 && img.height > 0)){
console.log("图片正确")
}else{
setBackgrund(backGroundImg,errImg);
}
},1000);
}else{
//图片地址为空,设置加载中图片
setBackgrund(backGroundImg,loadingImg);
//两秒后重新检测图片,为空就设置404图片,有值不作处理 上面会处理
setTimeout(function(){
if(!scope.value){
//设置404图片
setBackgrund(backGroundImg,errImg);
}
},2000);
}
});
function setBackgrund(backGroundImg,value){
backGroundImg.style.background="url("+value+") center no-repeat";
backGroundImg.style.backgroundSize="cover";
}
}
}
});
/** 图片加载失败默认图片指令*/
app.directive('whenerror', function(){
// Runs during compile
return {
link: function($scope, iElm, iAttrs, controller) {
//图片数据为空时
if(!iAttrs['src']){
changeSrc(iElm,iAttrs);
}
//图片数据不为空,但是无法访问时
var retryTimes = 0;
iElm.on('error', function(){
retryTimes++;
if(retryTimes>=2){
return;
}
changeSrc(iElm,iAttrs);
})
function changeSrc(iElm,iAttrs){
if(iAttrs['whenerror']=='small'){
iElm[0].src='img/404/4041.png'
}else if(iAttrs['whenerror']=='big'){
iElm[0].src='img/404/4042.png'
}else if(iAttrs['whenerror']=='homebig'){
iElm[0].src='img/imgs/homepage-sm.png'
}else{
iElm[0].src='img/404/404.png'
}
}
}
};
});