当通过ajax加载图像时,获得无限循环

我正在尝试使用户上传的文件在node.js中是私有的。 而且我正在使用angular来在客户端提供文件。

<div ng-repeat="message in messages"> <div class="details" ng-if="message.type == 'photo'"> <img ng-src="{{ chat_ctrl.getPhoto(message.photo, message.conversation_id, message.type) }}" class="message-photo" alt="{{ message.text }}"> <p>{{ message.text }}</p> <small am-time-ago="message.timestamp" am-preprocess="unix"></small> </div> </div> 

这是我用来获取文件的function。

  me.getPhoto = function(url, id, message_type){ if(message_type == 'photo'){ RequestsService.getPhoto(url, id).then(function(response){ console.log(response); //returns the data-uri of the image return response; }); }else{ return ''; } }; 

该函数从RequestService调用getPhoto方法,该请求向node.js服务器发出请求:

  function getPhoto(url, id){ var deferred = $q.defer(); var request = { method: 'GET', url: base_url + '/uploads' + url, params: {'url': url, 'id' : id} }; $http(request) .success(function(response){ $timeout.cancel(me.timer); deferred.resolve(response); }) .error(function(data){ deferred.reject(); }); me.requestTimeout(deferred); return deferred.promise; }; 

这是我得到的错误:

 Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting! Watchers fired in the last 5 iterations: [] 

服务器返回表示图像的data-uri。 我已经尝试使用ng-click来调用相同的方法,它返回的数据uri罚款:

 <img src="" ng-click="chat_ctrl.getPhoto(message.photo, message.conversation_id, message.type)" class="message-photo" alt="{{ message.text }}"> 

有任何想法吗?

更新

我试图直接返回从http请求中获得的数据,但是我仍然得到相同的错误。

 $http(request) .success(function(response){ //$timeout.cancel(me.timer); //deferred.resolve(response); return response; }) .error(function(data){ return data; //deferred.reject(); }); 

避免在ng-src使用asynchronous函数调用。 ng-src的expression式在每个digest上执行。

尝试首先加载控制器中的所有照片:

 loadPhotos(); loadPhotos = function() { for(var i=0,max=messages.length; i<max; i++) { me.getPhoto(i); } }; getPhoto = function(index){ if(messages[index].message_type == 'photo'){ RequestsService .getPhoto(messages[index].photo, messages[index].conversation_id) .then(function(response){ messages[index].photoSrc = response; }); } }; 

在你的模板中使用:

 <img ng-src="{{message.photoSrc}}" ... />