2014-09-24 26 views
0

在Angular中,我有加載背景圖像屬性的指令。我如何獲得背景圖像以便按需重新加載?如何重新加載一個指令中的CSS背景圖像

app.directive('profilePhotoPreview', function() { 
    return { 
     restrict: "A", 
     scope: { 
      uuid: "=" 
     }, 
     template: "", 
     link: function (scope, element, attrs) { 
      scope.$watch('uuid', function (value) { 
       console.log('profilePhotoPreview ',value); 
       if (scope.uuid) { 
        scope.preview = "url('"+conf.s3 + "user_profile_photos/" + scope.uuid + ".jpg')"; 

        var s={'width':'400px', 'height':'400px','background-image': scope.preview} 
        element.css(s); 
       } 

      }) 

     } 
    } 
}); 

在這種情況下,基礎照片已被更改(即新的個人資料照片已上傳),但url是相同的。

我試着在uuid變量上設置一個$ watch,並將它的值從null轉換回原來的值,以便將Angular重新渲染爲css,但這沒有任何效果。

+0

會這樣使用緩存的數據瀏覽器的結果? – 2014-09-24 13:44:37

回答

1

在這種情況下,瀏覽器已經緩存了該映像。要重新加載它,您可以將'?xxxx'添加到圖像url,其中'xxxx'是一個隨機字符串。

我的意思是,你只需要當你想重裝PIC改變你scope.preview變量:

scope.preview = "url('"+conf.s3 + "user_profile_photos/" + scope.uuid + ".jpg?"+getRandomInt(0, 10000)+")"; 

function getRandomInt(min, max) { 
    return Math.floor(Math.random() * (max - min + 1)) + min; 
} 
+0

這將導致所有用戶配置文件圖像總是被下載。 – cgTag 2014-09-24 13:50:00

+0

只有在更新圖片時才能添加'?xxxx'。所以在默認情況下,它將清晰的URL以'.jpg'結尾 – gorpacrate 2014-09-24 13:52:00

+0

在這裏最好使用ng-style,所以角度本身可以改變樣式,而不需要jquery。這會更清楚。 – gorpacrate 2014-09-24 13:53:17