This repository has been archived by the owner on Oct 26, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathtranslate.js
86 lines (85 loc) · 2.65 KB
/
translate.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
(function (ng) {
'use strict';
/* Services */
ng.module('translate', [], ['$provide', function ($provide) {
$provide.factory('translate', ['$log', function ($log) {
var
localizedStrings = {},
log = true,
keys, translation,
translate = function translate(sourceString) {
if (!sourceString) {
return '';
}
keys = sourceString.trim().split('.');
translation = localizedStrings;
keys.forEach(function (key) {
translation = (translation || {})[key];
});
if (typeof translation === 'string') {
return {
t: translation,
missing: false
};
}
if (log) {
$log.warn('Missing localisation for "' + sourceString + '"');
}
return {
t: sourceString,
missing: true
};
};
translate.t = function (sourceString) {
return translate(sourceString).t;
};
translate.add = function (translations) {
ng.extend(localizedStrings, translations);
};
translate.remove = function (key) {
if (localizedStrings[key]) {
delete localizedStrings[key];
return true;
}
return false;
};
translate.set = function (translations) {
localizedStrings = translations;
};
translate.logMissedHits = function (boolLog) {
log = boolLog;
};
return translate;
}]);
}]);
/* Directives */
ng.module('translate.directives', [], function ($compileProvider) {
$compileProvider.directive('translate', ['$compile', 'translate', function ($compile, translate) {
return {
priority: 10, //Should be evaluated befor e. G. pluralize
restrict: 'ECMA',
compile: function compile(el, attrs) {
var
translateInnerHtml = false,
attrsToTranslate;
if (attrs.translate) {
attrsToTranslate = attrs.translate.split(' ');
ng.forEach(attrsToTranslate, function (v) {
el.attr(v, translate(attrs[v]).t);
});
translateInnerHtml = attrsToTranslate.indexOf('innerHTML') >= 0;
} else {
translateInnerHtml = true;
}
return function preLink(scope, el) {
if (translateInnerHtml) {
var tr = translate(el.html());
el.html((tr.missing ? '<span class="missing-translation">' : '') + tr.t + (tr.missing ? '</span>' : ''));
}
$compile(el.contents())(scope);
};
}
};
}]);
});
}(angular));