【问题标题】:Forcing a ng-src reload强制 ng-src 重新加载
【发布时间】:2013-09-17 08:50:23
【问题描述】:

当图片的 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。
  • 可能是$scope.$apply ?
  • 将 url 设为空然后重新设置,会向服务器发送虚假请求,应避免这种情况。 $scope.$apply 不是问题。工厂函数的 anser 已经在 $rootScope.$apply

标签: angularjs


【解决方案1】:

一个简单的解决方法是向 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;
}]);

【讨论】:

  • $scope.imageUrl += '?' + 日期.now();
  • 必须将代码放在 $timeout(function() { (code here) });所以它不会破坏 $digest。
【解决方案2】:

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

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

这应该会强制它重新加载。

【讨论】:

    【解决方案3】:

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

    类似这样的:

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

    那么你可以这样使用它:

    &lt;img ng-src="{{yourImageUrl | randomSrc}}" /&gt;

    【讨论】:

      【解决方案4】:

      试试这个

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

      【讨论】:

        【解决方案5】:

        我采取了指令将随机参数放入 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>

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-04-16
          • 1970-01-01
          • 2012-06-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-08-29
          • 2012-11-04
          相关资源
          最近更新 更多