4

我正在使用Danial Farid 的 ng-file-upload 插件创建一个与 AWS S3 一起使用的简单图像上传页面。它具有一个简单的按钮来上传新图像和图像列表。像这样:

<ul>
    <li ng-repeat="image in product.images">
        <a class="thumbnail" href="{{ image }}" target="_blank">
          <img ng-src="{{ image }}" alt="image">
        </a>
    </li>
    <li>
        <div class="btn-image-upload" 
            ngf-select 
            ngf-change="upload($files)"
            ngf-accept="'image/*'"></div>
    </li>
</ul>

在我的控制器上:

$scope.upload = function (files) {

    var aws_policy, aws_policy_signature;

    if (files && files.length) {
        $http
            .get(API_URL+'/helper/aws_policy')
            .then(function(data) {
                aws_policy = data.data.policy;
                aws_policy_signature = data.data.signature;
                for (var i = 0; i < files.length; i++) {
                    var file = files[i];
                    var key = generate_aws_key() + '.' + file.name.split('.').pop();
                    var base_url = 'https://.../';

                    Upload
                    .upload({ ... })
                    .success(function( data, status, headers, config ) {

                        console.log($scope.product);
                        $scope.product.images.push( base_url + key );
                        console.log($scope.product);

                    });
                }
            });
    }
};

该文件正在正确上传(我204 Success从 AWS 得到了一个不错的结果),并且这两个console.log($scope.product)被调用以显示适当的结果(第二个以images数组上的项目为特色)。

事情就是这样。这个宝贝在我的开发机器上完美运行,但有时在登台或生产服务器上,图像列表没有更新$scope.product.images。有时,我的意思是它完成了 1/3 次。

总结

有时$scope.product.images,仅在我的生产服务器上,当在 AngularJS 摘要中更新时,DOM 不会更新。

我的编程经验告诉我,在这类事情中有时不是一个可接受的概念,它必须与出现此问题时总是发生的事情有关,但我进行了广泛的调试,未能找到真正的原因。想法?

4

1 回答 1

2

这很可能是由异步回调中的循环引起的:

您必须冻结 的值i

$scope.upload = function (files) {

    var aws_policy, aws_policy_signature;

    function upload(index) {
        var file = files[index];
        var key = generate_aws_key() + '.' + file.name.split('.').pop();
        var base_url = 'https://.../';

        Upload
        .upload({ ... })
        .success(function( data, status, headers, config ) {

            console.log($scope.product);
            $scope.product.images.push( base_url + key );
            console.log($scope.product);

        });
    }

    if (files && files.length) {
        $http
            .get(API_URL+'/helper/aws_policy')
            .then(function(data) {
                aws_policy = data.data.policy;
                aws_policy_signature = data.data.signature;
                for (var i = 0; i < files.length; i++) {
                    var file = files[i];
                    upload(i);
                }
            });
    }
};
于 2015-08-18T19:08:35.723 回答