2013-08-28 92 views
2

我對角度很新,所以在這裏。我有一個上傳頭像和一個縮略圖來顯示上傳頭像的圖像。我的問題是如何更新新上傳的頭像的縮略圖。因爲現在我必須先刷新頁面才能看到更改。如何在angularjs中同步更新值

下面是我的控制器一些代碼:

//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以上我給上傳按鈕。我在代碼中包含了如何上傳我的頭像,這可能對我的問題有所幫助。

+0

從服務器返回圖像的路徑或名稱,並更新回調中圖像的來源。 – tymeJV

+0

嗯,uploadAvatar的返回只是一個成功消息。而對於回調,我包含了$ scope.userAvatar();在我的uploadAvatar成功回調之後。但它沒有奏效。 :( – user2720708

+0

是否在'result.data'中包含圖像名稱? – tymeJV

回答

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();再次分配它。