-
Notifications
You must be signed in to change notification settings - Fork 152
Expand file tree
/
Copy pathdirective.js
More file actions
79 lines (68 loc) · 3.12 KB
/
directive.js
File metadata and controls
79 lines (68 loc) · 3.12 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
angular.module('gettext').directive('translate', function (gettextCatalog, $parse, $animate, $compile) {
// Trim polyfill for old browsers (instead of jQuery)
// Based on AngularJS-v1.2.2 (angular.js#620)
var trim = (function () {
if (!String.prototype.trim) {
return function (value) {
return (typeof value === 'string') ? value.replace(/^\s*/, '').replace(/\s*$/, '') : value;
};
}
return function (value) {
return (typeof value === 'string') ? value.trim() : value;
};
})();
function assert(condition, missing, found) {
if (!condition) {
throw new Error('You should add a ' + missing + ' attribute whenever you add a ' + found + ' attribute.');
}
}
return {
restrict: 'A',
terminal: true,
compile: function compile(element, attrs) {
// Validate attributes
assert(!attrs.translatePlural || attrs.translateN, 'translate-n', 'translate-plural');
assert(!attrs.translateN || attrs.translatePlural, 'translate-plural', 'translate-n');
var html = trim(element.html());
var translatePlural = attrs.translatePlural;
return {
post: function (scope, element, attrs) {
var countFn = $parse(attrs.translateN);
var pluralScope = null;
var msgidExp = attrs.translate ? $parse(attrs.translate) : function () { return html; };
function update() {
var msgid = msgidExp(scope);
if (!msgid) {
// wait until msgid is initialized
return;
}
// Fetch correct translated string.
var translated;
if (translatePlural) {
scope = pluralScope || (pluralScope = scope.$new());
scope.$count = countFn(scope);
translated = gettextCatalog.getPlural(scope.$count, msgid, translatePlural);
} else {
translated = gettextCatalog.getString(msgid);
}
// Swap in the translation
var newWrapper = angular.element('<span>' + translated + '</span>');
$compile(newWrapper.contents())(scope);
var oldContents = element.contents();
var newContents = newWrapper.contents();
$animate.enter(newContents, element);
$animate.leave(oldContents);
}
if (attrs.translateN) {
scope.$watch(attrs.translateN, update);
}
if (attrs.translate) {
scope.$watch(attrs.translate, update);
}
scope.$on('gettextLanguageChanged', update);
update();
}
};
}
};
});