Skip to content

Instantly share code, notes, and snippets.

@icholy
Last active August 29, 2015 14:11
Show Gist options
  • Save icholy/c7ac165bf42a260585a8 to your computer and use it in GitHub Desktop.
Save icholy/c7ac165bf42a260585a8 to your computer and use it in GitHub Desktop.
<!-- preload/refresh image every 5 seconds -->
<img refresh-src="images/foo.jpg" refresh-delay="5000" />
/// <reference path="../types/tsd.d.ts" />
/// <reference path="../services.ts" />
module Directives {
interface IRefreshSrcScope extends ng.IScope {
src: string;
delay: string;
}
export function RefreshSrcFactory(
$http: ng.IHttpService,
$interval: ng.IIntervalService
): ng.IDirective {
return {
restrict: 'A',
replace: true,
scope: {
'src': '@refreshSrc',
'delay': '@refreshDelay'
},
link: function (
$scope: IRefreshSrcScope,
element: JQuery,
attrs: ng.IAttributes
) {
element.attr("src", $scope.src);
var interval = null;
var clearInterval = function () {
if (interval !== null) {
$interval.cancel(interval);
interval = null;
}
};
var resetInterval = function () {
var delay = parseInt($scope.delay);
if (isNaN(delay)) {
delay = 1000;
}
clearInterval();
interval = $interval(() => {
var src = $scope.src + '?cacheBuster=' + new Date().getTime();
$http.get(src).then(
() => { element.attr("src", src)},
(err) => console.log("error loading:", src)
);
}, delay);
element.attr("src", $scope.src);
};
$scope.$watch("src", (src, prevSrc) => {
if (src !== prevSrc) {
resetInterval();
}
});
$scope.$watch("delay", (delay, prevDelay) => {
if (delay !== prevDelay) {
resetInterval();
}
});
$scope.$on("$destroy", clearInterval);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment