2

我对角度很陌生,所以就这样吧。我有一个上传头像和一个缩略图来显示上传头像的图像。我的问题是如何更新新上传的头像的缩略图。因为现在我必须先刷新页面才能看到更改。

这是我的控制器中的一些代码:

//get avatar
$scope.userAvatar = function() {
    Api.getAvatar($scope.security.currentUser.email)
    .then(function(result) {
        //success
        $scope.avatarImage = result.config.url;
    }, function(result) {
        //errors
        console.log(result);
    });
}

//validate avatar then upload avatar
$scope.validateAvatar = function(files) {
    var fd = new FormData();
    if(files.length > 0) 
    {
        $scope.filesize = files[0].size;
        $scope.filemaxsize = 25 * 1024;
        $scope.$apply();

    //Take the first selected file
    fd.append("avatarImage", files[0]);
        $scope.uploadAvatar = function() {
            Api.uploadAvatar($scope.security.currentUser.email, fd)
            .then(function(result) {
                console.log(result.data);
                //$scope.avatarImage = result.config.url; ////doesn't update the $scope.avatarImage
                //$scope.userAvatar(); //doesn't update the $scope.avatarImage
                Api.getAvatar($scope.security.currentUser.email)
                .then(function(result) {
                    //success
                    console.log('uploaded Image');
                    $scope.avatarImage = result.config.url;
                });
            }, function(result) {
                console.log(result);
            })
        };  
    }
};

在我的部分

<div id="show-avatar" class="col-sm-3 col-sm-offset-3">
    <img id="avatarbox" ng-src="{{avatarImage}}" >
</div>

在我上面的控制器代码中,我首先验证选择的图像,如果它不超过 25kb,我会显示上传按钮。我包含了有关如何上传头像的代码,也许它可能有助于解决我的问题。

4

1 回答 1

1

好的,我用下面的代码解决了我自己的问题。

$scope.validateAvatar = function(files) {
    var fd = new FormData();
    if(files.length > 0) 
    {
        $scope.filesize = files[0].size;
        $scope.filemaxsize = 25 * 1024;
        $scope.avatarImage = '';            
        //Take the first selected file
        fd.append("avatarImage", files[0]);
        $scope.uploadAvatar = function() {
            Api.uploadAvatar($scope.security.currentUser.email, fd)
            .then(function(result) {
                $scope.userAvatar();
            }, function(result) {
                console.log(result);
            })
        };  
        $scope.$apply();
    }
};

我重置了 $scope.avatarImage,然后使用 $scope.userAvatar(); 再次分配它。

于 2013-08-29T06:37:06.347 回答