数组中的图像对象未定义

时间:2015-08-25 14:00:18

标签: javascript arrays angularjs

我正在使用promises进行一些简单的图像预加载。此函数是较大的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控制台)

console

我可以访问$scope.abbreviations处的所有对象,并且在检查时定义了imgPath属性。

那么为什么$scope.abbreviations.imgPathundefined

2 个答案:

答案 0 :(得分:3)

$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;
    }

答案 1 :(得分:1)

要正确获取img路径,您需要关注[i],其中i是数组中对象的编号。

更改行

console.log($scope.abbreviations[i].imgPath);

然后你会得到结果,然后将它应用到需要实际值的地方。