-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathangular-refresh.js
62 lines (55 loc) · 2.13 KB
/
angular-refresh.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
angular.module('datarefresh', [])
.directive('angularRefresh', ['$parse', '$timeout', '$http', function ($parse, $timeout, $http) {
return {
restrict: 'E',
template: '<div></div>',
replace: true,
link: function (scope, element, attrs) {
console.log(element);
var isRunning = true;
var method = 'get';
var url = '';
function successFunction(data) {
if (data !== undefined && isRunning) {
try {
$parse(attrs.ngModel).assign(scope, data);
}
catch (error) {
//Just in case scope got detroyed while we were trying to update
console.log(error);
}
}
if (isRunning) {
$timeout(function () { refreshFromUrl(url, interval); }, interval);
}
}
function refreshFromUrl(url, interval) {
if (isNaN(interval)) {
interval = 2000;
}
$http[method](url).success(function (data, status, headers, config) {
successFunction(data);
})
.error(function (data, status, headers, config) {
console.log(data);
});
}
if (attrs.ngModel !== undefined && attrs.ngModel !== '' && attrs.url !== undefined && attrs.url !== '')
{
var interval = parseInt(attrs.interval);
if(isNaN(interval))
interval = 2000;
if(attrs.method !== undefined && attrs.method !== '') {
if(attrs.method.toLowerCase() == 'get' || attrs.method.toLowerCase()=='jsonp') {
method = attrs.method.toLowerCase();
}
}
url = attrs.url;
refreshFromUrl(url, interval);
}
scope.$on('$destroy', function () {
isRunning = false;
});
}
}
}]);