我正在使用Promise对图像进行一些简单的预加载。此函数是更大的Angular(1.3.15)自定义指令的一部分
JS
function preLoad() {
var deferred = $q.defer();
var imageArray = [];
for (var i = 0; i < $scope.abbreviations.length; i++) {
imageArray[i] = new Image();
imageArray[i].src = $scope.abbreviations.imgPath;
//logging
console.log(imageArray[i]);
console.log(imageArray[i].src);
console.log($scope.abbreviations);
console.log($scope.abbreviations.imgPath);
}
imageArray.forEach.onload = function () {
deferred.resolve();
console.log('Resolved');
}
imageArray.forEach.onerror = function () {
deferred.reject();
console.log('Rejected')
}
return deferred.promise;
}
abbreviations
具有以下格式:abbreviations: [
{
name: 'a<sup>o</sup>',
tag: 'anno',
imgPath: 'images/keypad/anno.png'
},
{
name: 'esq.',
tag: 'esquire',
imgPath: 'images/keypad/esquire.png'
},
{
name: 'ex<sup>t</sup>, exaite',
tag: 'examinant',
imgPath: 'images/keypad/examinant.png'
}
]
日志(Chrome控制台)
我可以在
$scope.abbreviations
上访问所有对象,并检查imgPath属性是否已定义。那么为什么
$scope.abbreviations.imgPath
是undefined
? 最佳答案
$scope.abbreviations
是一个数组。
因此修复如下:
function preLoad() {
var deferred = $q.defer();
var imageArray = [];
for (var i = 0; i < $scope.abbreviations.length; i++) {
var abb = $scope.abbreviations[i]; //assign to a variable and use it. if you are refering more than one places.
imageArray[i] = new Image();
imageArray[i].src = abb.imgPath;
//logging
console.log(imageArray[i]);
console.log(imageArray[i].src);
console.log(abb);
console.log(abb.imgPath);
}
imageArray.forEach.onload = function () {
deferred.resolve();
console.log('Resolved');
}
imageArray.forEach.onerror = function () {
deferred.reject();
console.log('Rejected')
}
return deferred.promise;
}