当图像的URL没有改变,但是它的内容有没有改变时,如何强制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
- })
- }
- }])
一个简单的解决方法是将一个唯一的时间戳附加到ng-src以强制重新加载图像,如下所示:
- $scope.$apply(function () {
- $scope.imageUrl = $scope.imageUrl + '?' + new Date().getTime();
- });
要么
- angular.module('ngSrcDemo',[])
- .controller('AppCtrl',function ($scope) {
- $scope.app = {
- imageUrl: "http://example.com/img.png"
- };
- var random = (new Date()).toString();
- $scope.imageSource = $scope.app.imageUrl + "?cb=" + random;
- }]);