Javascript 如果映像为onerror,如何获取错误映像的productName或productId
您好,我是angularjs的新手,我正在尝试获取Javascript 如果映像为onerror,如何获取错误映像的productName或productId,javascript,html,angularjs,Javascript,Html,Angularjs,您好,我是angularjs的新手,我正在尝试获取产品或产品id的名称,如果在标记中无法加载特定的产品图像,那么我可以使用该产品id来做一些事情,但是当图像无法加载时,我如何获取特定的产品id或名称 我在这里使用指令,并试图在指令链接函数中获取productId 控制器 这是我的template.html {{data.productName} 我的指令.js angular.module('myApp').controller("myCtrl",function($scope){ scope
产品
或产品
id的名称,如果在
标记中无法加载特定的产品图像,那么我可以使用该产品id
来做一些事情,但是当图像无法加载时,我如何获取特定的产品id或名称
我在这里使用指令,并试图在指令链接函数中获取productId
控制器
这是我的template.html
{{data.productName}
我的指令.js
angular.module('myApp').controller("myCtrl",function($scope){
scope.products=[
{ productName:"Mobile",
productImage:"someImage.jpg",
productId: 1
},
{ productName:"wallet",
productImage:"someImage22.jpg",
productId: 2
},
{ productName:"headphones",
productImage:"image3.jpg",
productId: 3
}
]
});
index.html
---------
<div ng-repeat="products in products">
<my-directive data="products"><my-directive>
</div>
my directive.html
.directive('myDirective',function($state){
return{
restrict:'E',
scope:{
data:'='
},
templateUrl:'template.html',
link: function(scope,elem,attr){
var image = document.getElementById('imageId');
image.onerror=function(){
console.log("image loading error") // here console is also not printing.
console.log("product ID") // here i want error loding image productId.
}
}
}
});
{{data.productName}
在您的情况下,使用OneError无法传递角度数据,即
数据(产品)
。onerror正在调用一个处于外部角度的函数。所以,我们得到了这个错误。我们只能在onerror=“fun(event)”
中传递事件,而不能传递任何内容。在上述代码中,属性名称仅用于保存产品数据。您还可以将该产品数据存储在另一个属性中。您好,我对错误图像使用以下指令:
<div>
<h2>{{data.productName}}</h2>
<a href="example.com"><img id="imageId" src="{{data.productImage}}"> </a>
</div>
并使用它:
angular.module('myApp')
.directive("myDirective", function() {
return {
restrict: "E",
templateUrl: 'my-directive.html',
scope: {
data: '='
}
};
})
.directive('checkImg', function() {
return {
restrict: 'EA',
link: function(scope, element, attrs) {
element.bind('error', function($event) {
console.log(JSON.parse(attrs.name)); // Here is your product
});
}
}
});
您是否尝试过使用scope.data.productId
?您必须在
的父范围中有一个范围变量products
,我用controller@charancherri更新了我的代码。我尝试了您的代码,但对我来说,它给出了一个类似以下的错误未捕获引用错误:getElem未在HTMLImageElement.onerror中定义((索引):1)onerror@(索引):1
@charancherryin代替var getElem
使用scope.getElem
我像你的代码一样更新了。我也得到了同样的错误@CharanCherrylast和final,使用函数getElem
并删除scope.getElem
等一下,我正在准备一个扑救器@CharanCherry
<div>
<h2>{{data.productName}}</h2>
<img ng-src="{{data.productImage}}" name="{{data}}" check-img>
</div>
angular
.module("myappName")
.directive('errSrc', function () {
return {
link: function(scope, element, attrs) {
element.bind('error', function() {
console.log(attrs);
// here you can catch the error of image
});
}
};
});
<img data-ng-src={{mysrc}} err-src />