-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathangular-timezone-select.js
More file actions
102 lines (95 loc) · 2.94 KB
/
angular-timezone-select.js
File metadata and controls
102 lines (95 loc) · 2.94 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
angular.module('angular-timezone-select', [])
.constant('_', _)
.constant('moment', moment)
.factory('timezones', ['_', 'moment', function(_, moment) {
return _.sortBy(_.map(moment.tz.names(), function(zoneName) {
return {
name: zoneName,
offset: 'UTC' + moment().tz(zoneName).format('Z')
};
}), 'offset');
}])
.factory('zones', ['_', function(_) {
var zones = [];
var grouped = _.groupBy(zones, function(zone) {
return zone.cca2;
});
return _.mapValues(grouped, function(countries) {
return _.map(countries, 'name');
});
}])
.directive('timezoneSelect', ['_', 'timezones', 'zones', '$timeout', function(_, timezones, zones, $timeout) {
return {
restrict: 'A',
scope: {
country: '=',
ngModel: '='
},
link: function(scope, elem, attrs) {
var $select2;
function transformTimezone(zone) {
return {
id: zone.name,
text: zone.name,
offset: zone.offset
};
}
function getTranslatedValue(key, defaultValue) {
return attrs['i18n' + _.capitalize(key)] || defaultValue;
}
scope.$watch('country', function(country) {
if ($select2) {
$select2.select2('destroy');
$select2.empty();
}
var groups = _.groupBy(timezones, function(zone) {
return !!(country && zones[country] && _.find(zones[country], function(zoneName) {
return zoneName === zone.name;
}));
});
var data = [
{
text: getTranslatedValue('utc', 'UTC'),
children: [
{
id: 'UTC',
text: getTranslatedValue('utc', 'UTC')
}
]
}
];
if (groups[true]) {
data.push({
text: getTranslatedValue('common', 'Common'),
children: _.map(groups[true], transformTimezone)
});
}
data.push({
text: getTranslatedValue('other', 'Other'),
children: _.map(groups[false], transformTimezone)
});
$select2 = elem.select2({
placeholder: 'Select a timezone',
allowClear: true,
width: 'resolve',
data: data,
templateSelection: function(selection) {
return selection.text;
},
templateResult: function(result) {
return result.offset
? $("<strong>" + result.id + "</strong> <small>" + result.offset + "</small>")
: result.text;
}
});
scope.$watch('ngModel', function(newValue) {
if (!!newValue) {
$timeout(function() {
$select2.val(newValue).trigger('change');
}, 0, false);
}
});
});
}
};
}]);