javascript – AngularJS使用ng-style设置宽度

我想在触发S3事件时动态调整div的大小.

在下面的代码中,我将progress变量作为参数发送到updateProgress函数.此函数位于我的Angular控制器的最高范围内.

s3.upload(params).on('httpUploadProgress', function(evt) {
        var progress;
        progress = Math.floor(evt.loaded * 100 / evt.total);
        updateProgress(progress);
    })
    .send(function(err, res, data) {
        if (err) {
            growl.error("We're having trouble uploading your image. Please try again!", {title: 'Whoops!', ttl: 5000});
            console.log('Error uploading' + err);
        } else {
            imgLocation = res.Location;
            postToFirebase(imgLocation);
        }
    });

这是我的updateProgress函数

function updateProgress(percent) {
    $scope.progressBar = {
        'width': percent + '%'
    }
}

HTML

< div ng-style =“progressBar”class =“shot__image – post__progress”>< / div>

我可以成功控制AWS事件和进度值.但是,当我上传图像时,宽度永远不会改变.

最佳答案 Phil在这篇帖子的评论中回答.

Assuming the s3 library is not part of or privy to the Angular digest
cycle, you need to wrap the changes to $scope properties in
$scope.$apply or $scope.$applyAsync. See
docs.angularjs.org/api/ng/type/$rootScope.Scope#$apply. User Raghu
answered this earlier but was downvoted for some reason

解决方案是在updateProgress fn中简单地调用$scope.$apply().

点赞