强制ng-src重新加载


77

当图像的url未更改但其内容已更改时,如何强制angularjs重新加载具有ng-src属性的图像?

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

执行文件上传的uploadReplace服务将替换图像的内容,而不是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;
        }
    }
}]);

当uploadReplace返回时,我不知道如何强制重新加载图像

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 
        })
    }
}])

设置为urlprofilephoto空,然后再次将其设置为URL。
Chandermani

可能与$scope.$apply
伊万·切尔尼赫

将url设置为空,然后再次进行设置,将虚假请求发送到服务器,应避免这种情况。$ scope。$ apply不是问题。工厂函数的
分析器

Answers:


77

一个简单的解决方法是向ng-src附加唯一的时间戳,以强制图像重新加载,如下所示:

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

要么

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;
}]);

1
$ scope.imageUrl + ='?' + Date.now();
heychez

28

也许就像将反缓存查询字符串添加到图像URL一样简单?即。

var imageUrl = 'http://i.imgur.com/SVFyXFX.jpg';
$scope.decachedImageUrl = imageUrl + '?decache=' + Math.random();

这将迫使它重新加载。


16

“角度方法”可能正在创建您自己的过滤器,以向图像URL添加随机querystring参数。

像这样:

.filter("randomSrc", function () {
    return function (input) {
        if (input) {
            var sep = input.indexOf("?") != -1 ? "&" : "?";
            return input + sep + "r=" + Math.round(Math.random() * 999999);
        }
    }
})

然后,您可以像这样使用它:

<img ng-src="{{yourImageUrl | randomSrc}}" />


6

试试这个

app.controller('ctrl', ['$scope', 'R4aFact', function($scope, R4aFact){
$scope.clickReplace = function() {
    R4aFact.uploadReplace($scope.imgfile, $scope.pid).then(function(response){
        $scope.urlprofilephoto  = response + "?" + new Date().getTime(); //here response is ur image name with path.
    });
}
 }])

0

我求助于一个指令来将随机参数放入src中,但是仅当图像更改时才这样做,因此我对缓存的了解不多。

当他们通过AJAX更新用户的个人资料照片时,我用它来更新它,这种情况很少发生。

(function() {
  "use strict";

  angular
    .module("exampleApp", [])
    .directive("eaImgSrc", directiveConstructor);

  function directiveConstructor() {
    return { link: link };

    function link(scope, element, attrs) {
      scope.$watch(attrs.eaImgSrc, function(currentSrc, oldSrc) {
        if (currentSrc) {
          // check currentSrc is not a data url,
          // since you can't append a param to that
          if (oldSrc && !currentSrc.match(/^data/)) {
            setSrc(currentSrc + "?=" + new Date().getTime());
          } else {
            setSrc(currentSrc);
          }
        } else {
          setSrc(null);
        }
      })

      function setSrc(src) { element[0].src = src; }
    }
  }
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="exampleApp">
  <div>
    <img ea-img-src="src"></img>
  </div>

  <button ng-click="src = 'http://placehold.it/100x100/FF0000'">IMG 1</button>
  <button ng-click="src = 'http://placehold.it/100x100/0000FF'">IMG 2</button>
  <button ng-click="src = 'http://placehold.it/100x100/00FF00'">IMG 3</button>
</div>

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.