Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
806 views
in Technique[技术] by (71.8m points)

angularjs - Forcing a ng-src reload

How can I force angularjs to reload an image with an ng-src attribute, when the url of the image has not changed, but its contents has?

<div ng-controller='ctrl'>
    <img ng-src="{{urlprofilephoto}}">
</div>

An uploadReplace service that performs a file upload, is replacing the content of the image, but not the url.

app.factory('R4aFact', ['$http', '$q', '$route', '$window', '$rootScope',
function($http, $q, $route, $window, $rootScope) {
    return {
        uploadReplace: function(imgfile, profileid) {
            var xhr = new XMLHttpRequest(),
                fd = new FormData(),
                d = $q.defer();
            fd.append('profileid', profileid);
            fd.append('filedata', imgfile);
            xhr.onload = function(ev) {
                var data = JSON.parse(this.responseText);
                $rootScope.$apply(function(){
                    if (data.status == 'OK') {
                        d.resolve(data);
                    } else {
                        d.reject(data);
                    }
                });
            }
            xhr.open('post', '/profile/replacePhoto', true)
            xhr.send(fd)
            return d.promise;
        }
    }
}]);

When the uploadReplace returns, I don't know how I can force the image to reload

app.controller('ctrl', ['$scope', 'R4aFact', function($scope, R4aFact){
    $scope.clickReplace = function() {
        R4aFact.uploadReplace($scope.imgfile, $scope.pid).then(function(){
            // ??  here I need to force to reload the imgsrc 
        })
    }
}])
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

An easy workaround is to append a unique timestamp to ng-src to force image reload as follows:

$scope.$apply(function () {
    $scope.imageUrl = $scope.imageUrl + '?' + new Date().getTime();
});

or

angular.module('ngSrcDemo', [])
    .controller('AppCtrl', ['$scope', function ($scope) {
    $scope.app = {
        imageUrl: "http://example.com/img.png"
    };
    var random = (new Date()).toString();
    $scope.imageSource = $scope.app.imageUrl + "?cb=" + random;
}]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...