Reputation: 2697
I have the following needs:
1) I'd like to be able to intercept calls to img ng-src
via my http interceptor. Given that ng-src does not get routed to http interceptors, I am using this http-src directive https://stackoverflow.com/a/29606436/1361529
2) The problem however is that this directive only works once - it replaces the "src" attribute with the image, so the image only loads once and does not change.
What I mean is my template has the following code:
<span ng-repeat="monitor in MontageMonitors>
<img id="img-$index" http-src="{{LoginData.streamingurl}}/nph-zms?mode=single&monitor={{monitor.Monitor.Id}}&scale={{LoginData.montageQuality}}{{$root.authSession}}&rand={{$root.rand}}" ng-click="openModal(monitor.Monitor.Id, monitor.Monitor.Controllable, monitor.Monitor.ControlId)" />
</span>
This image is reloaded every 1 second via a timer in my code, but since the http-src directive essentially replaces the src attribute with an inline image, it doesn't update.
How do I solve this?
thanks
Upvotes: 0
Views: 2872
Reputation: 3987
In your custom http-src
directive's link function, you would need to $observe the attribute and make your $http call each time it changes.
Something like this (based on the code from the SO answer you linked to):
angular.module('myApp', [])
.directive('httpSrc', httpSrcDirective);
httpSrcDirective.$inject = ['$http'];
function httpSrcDirective($http) {
return {
link: postLink,
restrict: 'A'
};
function postLink(scope, element, attrs) {
var requestConfig = {
method: 'GET',
responseType: 'arraybuffer',
cache: 'true'
};
function base64Img(data) {
var arr = new Uint8Array(data);
var raw = '';
var i, j, subArray, chunk = 5000;
for (i = 0, j = arr.length; i < j; i += chunk) {
subArray = arr.subarray(i, i + chunk);
raw += String.fromCharCode.apply(null, subArray);
}
return btoa(raw);
};
attrs.$observe('httpSrc', function(newValue) {
requestConfig.url = newValue;
$http(requestConfig)
.then(function(data) {
attrs.$set('src', "data:image/jpeg;base64," + base64Img(data));
});
});
}
}
Upvotes: 3