强制ng-src重新加载

时间:2013-09-17 08:50:23

标签: angularjs

当图像的网址没有改变但是其内容有吗?

时,如何强制angularjs重新加载具有ng-src属性的图像?
<div ng-controller='ctrl'>
    <img ng-src="{{urlprofilephoto}}">
</div>

执行文件上传的uploadReplace服务正在替换图片的内容,而不是网址。

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

5 个答案:

答案 0 :(得分:76)

一个简单的解决方法是在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 :(得分:27)

也许它可以像在图像URL中添加decache查询字符串一样简单?即

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

这应该强制它重新加载。

答案 2 :(得分:16)

&#34;角度方法&#34;可以创建自己的过滤器,将随机查询字符串参数添加到图像URL。

这样的事情:

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

然后你可以像这样使用它:

&#13;
&#13;
<img ng-src="{{yourImageUrl | randomSrc}}" />
&#13;
&#13;
&#13;

答案 3 :(得分: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.
    });
}
 }])

答案 4 :(得分:0)

我使用了一个指令将随机参数放在src中,但是只有当图像发生变化时,我才不会因为缓存而搞得那么多。

我用它来更新用户在导航栏中的个人资料图片,当他们通过AJAX更新时,这种情况并不经常发生。

&#13;
&#13;
(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; }
    }
  }
})();
&#13;
<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>
&#13;
&#13;
&#13;