source

ng-src 강제 새로고침

factcode 2023. 3. 10. 22:47
반응형

ng-src 강제 새로고침

이미지의 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 
        })
    }
}])

간단한 회피책은 다음과 같이 고유한 타임스탬프를 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;
}]);

이미지 URL에 디캐시 쿼리 문자열을 추가하는 것만으로 간단할 수 있습니다.

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

이것에 의해, 강제적으로 새로고침 됩니다.

"각선 접근법"은 이미지 URL에 임의 쿼리 문자열 매개 변수를 추가하는 자체 필터를 만드는 것입니다.

다음과 같은 경우:

.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}}" />

시험해 보다

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

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>

언급URL : https://stackoverflow.com/questions/18845298/forcing-a-ng-src-reload

반응형