angular-translate.js 111 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266
  1. /*!
  2. * angular-translate - v2.9.0 - 2016-01-24
  3. *
  4. * Copyright (c) 2016 The angular-translate team, Pascal Precht; Licensed MIT
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining a copy
  7. * of this software and associated documentation files (the "Software"), to deal
  8. * in the Software without restriction, including without limitation the rights
  9. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. * copies of the Software, and to permit persons to whom the Software is
  11. * furnished to do so, subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included in
  14. * all copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. * THE SOFTWARE.
  23. *
  24. */
  25. (function (root, factory) {
  26. if (typeof define === 'function' && define.amd) {
  27. // AMD. Register as an anonymous module unless amdModuleId is set
  28. define([], function () {
  29. return (factory());
  30. });
  31. } else if (typeof exports === 'object') {
  32. // Node. Does not work with strict CommonJS, but
  33. // only CommonJS-like environments that support module.exports,
  34. // like Node.
  35. module.exports = factory();
  36. } else {
  37. factory();
  38. }
  39. }(this, function () {
  40. /**
  41. * @ngdoc overview
  42. * @name pascalprecht.translate
  43. *
  44. * @description
  45. * The main module which holds everything together.
  46. */
  47. angular.module('pascalprecht.translate', ['ng'])
  48. .run(runTranslate);
  49. function runTranslate($translate) {
  50. 'use strict';
  51. var key = $translate.storageKey(),
  52. storage = $translate.storage();
  53. var fallbackFromIncorrectStorageValue = function () {
  54. var preferred = $translate.preferredLanguage();
  55. if (angular.isString(preferred)) {
  56. $translate.use(preferred);
  57. // $translate.use() will also remember the language.
  58. // So, we don't need to call storage.put() here.
  59. } else {
  60. storage.put(key, $translate.use());
  61. }
  62. };
  63. fallbackFromIncorrectStorageValue.displayName = 'fallbackFromIncorrectStorageValue';
  64. if (storage) {
  65. if (!storage.get(key)) {
  66. fallbackFromIncorrectStorageValue();
  67. } else {
  68. $translate.use(storage.get(key))['catch'](fallbackFromIncorrectStorageValue);
  69. }
  70. } else if (angular.isString($translate.preferredLanguage())) {
  71. $translate.use($translate.preferredLanguage());
  72. }
  73. }
  74. runTranslate.$inject = ['$translate'];
  75. runTranslate.displayName = 'runTranslate';
  76. /**
  77. * @ngdoc object
  78. * @name pascalprecht.translate.$translateSanitizationProvider
  79. *
  80. * @description
  81. *
  82. * Configurations for $translateSanitization
  83. */
  84. angular.module('pascalprecht.translate').provider('$translateSanitization', $translateSanitizationProvider);
  85. function $translateSanitizationProvider () {
  86. 'use strict';
  87. var $sanitize,
  88. currentStrategy = null, // TODO change to either 'sanitize', 'escape' or ['sanitize', 'escapeParameters'] in 3.0.
  89. hasConfiguredStrategy = false,
  90. hasShownNoStrategyConfiguredWarning = false,
  91. strategies;
  92. /**
  93. * Definition of a sanitization strategy function
  94. * @callback StrategyFunction
  95. * @param {string|object} value - value to be sanitized (either a string or an interpolated value map)
  96. * @param {string} mode - either 'text' for a string (translation) or 'params' for the interpolated params
  97. * @return {string|object}
  98. */
  99. /**
  100. * @ngdoc property
  101. * @name strategies
  102. * @propertyOf pascalprecht.translate.$translateSanitizationProvider
  103. *
  104. * @description
  105. * Following strategies are built-in:
  106. * <dl>
  107. * <dt>sanitize</dt>
  108. * <dd>Sanitizes HTML in the translation text using $sanitize</dd>
  109. * <dt>escape</dt>
  110. * <dd>Escapes HTML in the translation</dd>
  111. * <dt>sanitizeParameters</dt>
  112. * <dd>Sanitizes HTML in the values of the interpolation parameters using $sanitize</dd>
  113. * <dt>escapeParameters</dt>
  114. * <dd>Escapes HTML in the values of the interpolation parameters</dd>
  115. * <dt>escaped</dt>
  116. * <dd>Support legacy strategy name 'escaped' for backwards compatibility (will be removed in 3.0)</dd>
  117. * </dl>
  118. *
  119. */
  120. strategies = {
  121. sanitize: function (value, mode) {
  122. if (mode === 'text') {
  123. value = htmlSanitizeValue(value);
  124. }
  125. return value;
  126. },
  127. escape: function (value, mode) {
  128. if (mode === 'text') {
  129. value = htmlEscapeValue(value);
  130. }
  131. return value;
  132. },
  133. sanitizeParameters: function (value, mode) {
  134. if (mode === 'params') {
  135. value = mapInterpolationParameters(value, htmlSanitizeValue);
  136. }
  137. return value;
  138. },
  139. escapeParameters: function (value, mode) {
  140. if (mode === 'params') {
  141. value = mapInterpolationParameters(value, htmlEscapeValue);
  142. }
  143. return value;
  144. }
  145. };
  146. // Support legacy strategy name 'escaped' for backwards compatibility.
  147. // TODO should be removed in 3.0
  148. strategies.escaped = strategies.escapeParameters;
  149. /**
  150. * @ngdoc function
  151. * @name pascalprecht.translate.$translateSanitizationProvider#addStrategy
  152. * @methodOf pascalprecht.translate.$translateSanitizationProvider
  153. *
  154. * @description
  155. * Adds a sanitization strategy to the list of known strategies.
  156. *
  157. * @param {string} strategyName - unique key for a strategy
  158. * @param {StrategyFunction} strategyFunction - strategy function
  159. * @returns {object} this
  160. */
  161. this.addStrategy = function (strategyName, strategyFunction) {
  162. strategies[strategyName] = strategyFunction;
  163. return this;
  164. };
  165. /**
  166. * @ngdoc function
  167. * @name pascalprecht.translate.$translateSanitizationProvider#removeStrategy
  168. * @methodOf pascalprecht.translate.$translateSanitizationProvider
  169. *
  170. * @description
  171. * Removes a sanitization strategy from the list of known strategies.
  172. *
  173. * @param {string} strategyName - unique key for a strategy
  174. * @returns {object} this
  175. */
  176. this.removeStrategy = function (strategyName) {
  177. delete strategies[strategyName];
  178. return this;
  179. };
  180. /**
  181. * @ngdoc function
  182. * @name pascalprecht.translate.$translateSanitizationProvider#useStrategy
  183. * @methodOf pascalprecht.translate.$translateSanitizationProvider
  184. *
  185. * @description
  186. * Selects a sanitization strategy. When an array is provided the strategies will be executed in order.
  187. *
  188. * @param {string|StrategyFunction|array} strategy The sanitization strategy / strategies which should be used. Either a name of an existing strategy, a custom strategy function, or an array consisting of multiple names and / or custom functions.
  189. * @returns {object} this
  190. */
  191. this.useStrategy = function (strategy) {
  192. hasConfiguredStrategy = true;
  193. currentStrategy = strategy;
  194. return this;
  195. };
  196. /**
  197. * @ngdoc object
  198. * @name pascalprecht.translate.$translateSanitization
  199. * @requires $injector
  200. * @requires $log
  201. *
  202. * @description
  203. * Sanitizes interpolation parameters and translated texts.
  204. *
  205. */
  206. this.$get = ['$injector', '$log', function ($injector, $log) {
  207. var cachedStrategyMap = {};
  208. var applyStrategies = function (value, mode, selectedStrategies) {
  209. angular.forEach(selectedStrategies, function (selectedStrategy) {
  210. if (angular.isFunction(selectedStrategy)) {
  211. value = selectedStrategy(value, mode);
  212. } else if (angular.isFunction(strategies[selectedStrategy])) {
  213. value = strategies[selectedStrategy](value, mode);
  214. } else if (angular.isString(strategies[selectedStrategy])) {
  215. if (!cachedStrategyMap[strategies[selectedStrategy]]) {
  216. try {
  217. cachedStrategyMap[strategies[selectedStrategy]] = $injector.get(strategies[selectedStrategy]);
  218. } catch (e) {
  219. cachedStrategyMap[strategies[selectedStrategy]] = function() {};
  220. throw new Error('pascalprecht.translate.$translateSanitization: Unknown sanitization strategy: \'' + selectedStrategy + '\'');
  221. }
  222. }
  223. value = cachedStrategyMap[strategies[selectedStrategy]](value, mode);
  224. } else {
  225. throw new Error('pascalprecht.translate.$translateSanitization: Unknown sanitization strategy: \'' + selectedStrategy + '\'');
  226. }
  227. });
  228. return value;
  229. };
  230. // TODO: should be removed in 3.0
  231. var showNoStrategyConfiguredWarning = function () {
  232. if (!hasConfiguredStrategy && !hasShownNoStrategyConfiguredWarning) {
  233. $log.warn('pascalprecht.translate.$translateSanitization: No sanitization strategy has been configured. This can have serious security implications. See http://angular-translate.github.io/docs/#/guide/19_security for details.');
  234. hasShownNoStrategyConfiguredWarning = true;
  235. }
  236. };
  237. if ($injector.has('$sanitize')) {
  238. $sanitize = $injector.get('$sanitize');
  239. }
  240. return {
  241. /**
  242. * @ngdoc function
  243. * @name pascalprecht.translate.$translateSanitization#useStrategy
  244. * @methodOf pascalprecht.translate.$translateSanitization
  245. *
  246. * @description
  247. * Selects a sanitization strategy. When an array is provided the strategies will be executed in order.
  248. *
  249. * @param {string|StrategyFunction|array} strategy The sanitization strategy / strategies which should be used. Either a name of an existing strategy, a custom strategy function, or an array consisting of multiple names and / or custom functions.
  250. */
  251. useStrategy: (function (self) {
  252. return function (strategy) {
  253. self.useStrategy(strategy);
  254. };
  255. })(this),
  256. /**
  257. * @ngdoc function
  258. * @name pascalprecht.translate.$translateSanitization#sanitize
  259. * @methodOf pascalprecht.translate.$translateSanitization
  260. *
  261. * @description
  262. * Sanitizes a value.
  263. *
  264. * @param {string|object} value The value which should be sanitized.
  265. * @param {string} mode The current sanitization mode, either 'params' or 'text'.
  266. * @param {string|StrategyFunction|array} [strategy] Optional custom strategy which should be used instead of the currently selected strategy.
  267. * @returns {string|object} sanitized value
  268. */
  269. sanitize: function (value, mode, strategy) {
  270. if (!currentStrategy) {
  271. showNoStrategyConfiguredWarning();
  272. }
  273. if (arguments.length < 3) {
  274. strategy = currentStrategy;
  275. }
  276. if (!strategy) {
  277. return value;
  278. }
  279. var selectedStrategies = angular.isArray(strategy) ? strategy : [strategy];
  280. return applyStrategies(value, mode, selectedStrategies);
  281. }
  282. };
  283. }];
  284. var htmlEscapeValue = function (value) {
  285. var element = angular.element('<div></div>');
  286. element.text(value); // not chainable, see #1044
  287. return element.html();
  288. };
  289. var htmlSanitizeValue = function (value) {
  290. if (!$sanitize) {
  291. throw new Error('pascalprecht.translate.$translateSanitization: Error cannot find $sanitize service. Either include the ngSanitize module (https://docs.angularjs.org/api/ngSanitize) or use a sanitization strategy which does not depend on $sanitize, such as \'escape\'.');
  292. }
  293. return $sanitize(value);
  294. };
  295. var mapInterpolationParameters = function (value, iteratee) {
  296. if (angular.isObject(value)) {
  297. var result = angular.isArray(value) ? [] : {};
  298. angular.forEach(value, function (propertyValue, propertyKey) {
  299. result[propertyKey] = mapInterpolationParameters(propertyValue, iteratee);
  300. });
  301. return result;
  302. } else if (angular.isNumber(value)) {
  303. return value;
  304. } else {
  305. return iteratee(value);
  306. }
  307. };
  308. }
  309. /**
  310. * @ngdoc object
  311. * @name pascalprecht.translate.$translateProvider
  312. * @description
  313. *
  314. * $translateProvider allows developers to register translation-tables, asynchronous loaders
  315. * and similar to configure translation behavior directly inside of a module.
  316. *
  317. */
  318. angular.module('pascalprecht.translate')
  319. .constant('pascalprechtTranslateOverrider', {})
  320. .provider('$translate', $translate);
  321. function $translate($STORAGE_KEY, $windowProvider, $translateSanitizationProvider, pascalprechtTranslateOverrider) {
  322. 'use strict';
  323. var $translationTable = {},
  324. $preferredLanguage,
  325. $availableLanguageKeys = [],
  326. $languageKeyAliases,
  327. $fallbackLanguage,
  328. $fallbackWasString,
  329. $uses,
  330. $nextLang,
  331. $storageFactory,
  332. $storageKey = $STORAGE_KEY,
  333. $storagePrefix,
  334. $missingTranslationHandlerFactory,
  335. $interpolationFactory,
  336. $interpolatorFactories = [],
  337. $loaderFactory,
  338. $cloakClassName = 'translate-cloak',
  339. $loaderOptions,
  340. $notFoundIndicatorLeft,
  341. $notFoundIndicatorRight,
  342. $postCompilingEnabled = false,
  343. $forceAsyncReloadEnabled = false,
  344. $nestedObjectDelimeter = '.',
  345. $isReady = false,
  346. loaderCache,
  347. directivePriority = 0,
  348. statefulFilter = true,
  349. uniformLanguageTagResolver = 'default',
  350. languageTagResolver = {
  351. 'default': function (tag) {
  352. return (tag || '').split('-').join('_');
  353. },
  354. java: function (tag) {
  355. var temp = (tag || '').split('-').join('_');
  356. var parts = temp.split('_');
  357. return parts.length > 1 ? (parts[0].toLowerCase() + '_' + parts[1].toUpperCase()) : temp;
  358. },
  359. bcp47: function (tag) {
  360. var temp = (tag || '').split('_').join('-');
  361. var parts = temp.split('-');
  362. return parts.length > 1 ? (parts[0].toLowerCase() + '-' + parts[1].toUpperCase()) : temp;
  363. }
  364. };
  365. var version = '2.9.0';
  366. // tries to determine the browsers language
  367. var getFirstBrowserLanguage = function () {
  368. // internal purpose only
  369. if (angular.isFunction(pascalprechtTranslateOverrider.getLocale)) {
  370. return pascalprechtTranslateOverrider.getLocale();
  371. }
  372. var nav = $windowProvider.$get().navigator,
  373. browserLanguagePropertyKeys = ['language', 'browserLanguage', 'systemLanguage', 'userLanguage'],
  374. i,
  375. language;
  376. // support for HTML 5.1 "navigator.languages"
  377. if (angular.isArray(nav.languages)) {
  378. for (i = 0; i < nav.languages.length; i++) {
  379. language = nav.languages[i];
  380. if (language && language.length) {
  381. return language;
  382. }
  383. }
  384. }
  385. // support for other well known properties in browsers
  386. for (i = 0; i < browserLanguagePropertyKeys.length; i++) {
  387. language = nav[browserLanguagePropertyKeys[i]];
  388. if (language && language.length) {
  389. return language;
  390. }
  391. }
  392. return null;
  393. };
  394. getFirstBrowserLanguage.displayName = 'angular-translate/service: getFirstBrowserLanguage';
  395. // tries to determine the browsers locale
  396. var getLocale = function () {
  397. var locale = getFirstBrowserLanguage() || '';
  398. if (languageTagResolver[uniformLanguageTagResolver]) {
  399. locale = languageTagResolver[uniformLanguageTagResolver](locale);
  400. }
  401. return locale;
  402. };
  403. getLocale.displayName = 'angular-translate/service: getLocale';
  404. /**
  405. * @name indexOf
  406. * @private
  407. *
  408. * @description
  409. * indexOf polyfill. Kinda sorta.
  410. *
  411. * @param {array} array Array to search in.
  412. * @param {string} searchElement Element to search for.
  413. *
  414. * @returns {int} Index of search element.
  415. */
  416. var indexOf = function(array, searchElement) {
  417. for (var i = 0, len = array.length; i < len; i++) {
  418. if (array[i] === searchElement) {
  419. return i;
  420. }
  421. }
  422. return -1;
  423. };
  424. /**
  425. * @name trim
  426. * @private
  427. *
  428. * @description
  429. * trim polyfill
  430. *
  431. * @returns {string} The string stripped of whitespace from both ends
  432. */
  433. var trim = function() {
  434. return this.toString().replace(/^\s+|\s+$/g, '');
  435. };
  436. var negotiateLocale = function (preferred) {
  437. if(!preferred) {
  438. return;
  439. }
  440. var avail = [],
  441. locale = angular.lowercase(preferred),
  442. i = 0,
  443. n = $availableLanguageKeys.length;
  444. for (; i < n; i++) {
  445. avail.push(angular.lowercase($availableLanguageKeys[i]));
  446. }
  447. // Check for an exact match in our list of available keys
  448. if (indexOf(avail, locale) > -1) {
  449. return preferred;
  450. }
  451. if ($languageKeyAliases) {
  452. var alias;
  453. for (var langKeyAlias in $languageKeyAliases) {
  454. var hasWildcardKey = false;
  455. var hasExactKey = Object.prototype.hasOwnProperty.call($languageKeyAliases, langKeyAlias) &&
  456. angular.lowercase(langKeyAlias) === angular.lowercase(preferred);
  457. if (langKeyAlias.slice(-1) === '*') {
  458. hasWildcardKey = langKeyAlias.slice(0, -1) === preferred.slice(0, langKeyAlias.length-1);
  459. }
  460. if (hasExactKey || hasWildcardKey) {
  461. alias = $languageKeyAliases[langKeyAlias];
  462. if (indexOf(avail, angular.lowercase(alias)) > -1) {
  463. return alias;
  464. }
  465. }
  466. }
  467. }
  468. // Check for a language code without region
  469. var parts = preferred.split('_');
  470. if (parts.length > 1 && indexOf(avail, angular.lowercase(parts[0])) > -1) {
  471. return parts[0];
  472. }
  473. // If everything fails, return undefined.
  474. return;
  475. };
  476. /**
  477. * @ngdoc function
  478. * @name pascalprecht.translate.$translateProvider#translations
  479. * @methodOf pascalprecht.translate.$translateProvider
  480. *
  481. * @description
  482. * Registers a new translation table for specific language key.
  483. *
  484. * To register a translation table for specific language, pass a defined language
  485. * key as first parameter.
  486. *
  487. * <pre>
  488. * // register translation table for language: 'de_DE'
  489. * $translateProvider.translations('de_DE', {
  490. * 'GREETING': 'Hallo Welt!'
  491. * });
  492. *
  493. * // register another one
  494. * $translateProvider.translations('en_US', {
  495. * 'GREETING': 'Hello world!'
  496. * });
  497. * </pre>
  498. *
  499. * When registering multiple translation tables for for the same language key,
  500. * the actual translation table gets extended. This allows you to define module
  501. * specific translation which only get added, once a specific module is loaded in
  502. * your app.
  503. *
  504. * Invoking this method with no arguments returns the translation table which was
  505. * registered with no language key. Invoking it with a language key returns the
  506. * related translation table.
  507. *
  508. * @param {string} key A language key.
  509. * @param {object} translationTable A plain old JavaScript object that represents a translation table.
  510. *
  511. */
  512. var translations = function (langKey, translationTable) {
  513. if (!langKey && !translationTable) {
  514. return $translationTable;
  515. }
  516. if (langKey && !translationTable) {
  517. if (angular.isString(langKey)) {
  518. return $translationTable[langKey];
  519. }
  520. } else {
  521. if (!angular.isObject($translationTable[langKey])) {
  522. $translationTable[langKey] = {};
  523. }
  524. angular.extend($translationTable[langKey], flatObject(translationTable));
  525. }
  526. return this;
  527. };
  528. this.translations = translations;
  529. /**
  530. * @ngdoc function
  531. * @name pascalprecht.translate.$translateProvider#cloakClassName
  532. * @methodOf pascalprecht.translate.$translateProvider
  533. *
  534. * @description
  535. *
  536. * Let's you change the class name for `translate-cloak` directive.
  537. * Default class name is `translate-cloak`.
  538. *
  539. * @param {string} name translate-cloak class name
  540. */
  541. this.cloakClassName = function (name) {
  542. if (!name) {
  543. return $cloakClassName;
  544. }
  545. $cloakClassName = name;
  546. return this;
  547. };
  548. /**
  549. * @ngdoc function
  550. * @name pascalprecht.translate.$translateProvider#nestedObjectDelimeter
  551. * @methodOf pascalprecht.translate.$translateProvider
  552. *
  553. * @description
  554. *
  555. * Let's you change the delimiter for namespaced translations.
  556. * Default delimiter is `.`.
  557. *
  558. * @param {string} delimiter namespace separator
  559. */
  560. this.nestedObjectDelimeter = function (delimiter) {
  561. if (!delimiter) {
  562. return $nestedObjectDelimeter;
  563. }
  564. $nestedObjectDelimeter = delimiter;
  565. return this;
  566. };
  567. /**
  568. * @name flatObject
  569. * @private
  570. *
  571. * @description
  572. * Flats an object. This function is used to flatten given translation data with
  573. * namespaces, so they are later accessible via dot notation.
  574. */
  575. var flatObject = function (data, path, result, prevKey) {
  576. var key, keyWithPath, keyWithShortPath, val;
  577. if (!path) {
  578. path = [];
  579. }
  580. if (!result) {
  581. result = {};
  582. }
  583. for (key in data) {
  584. if (!Object.prototype.hasOwnProperty.call(data, key)) {
  585. continue;
  586. }
  587. val = data[key];
  588. if (angular.isObject(val)) {
  589. flatObject(val, path.concat(key), result, key);
  590. } else {
  591. keyWithPath = path.length ? ('' + path.join($nestedObjectDelimeter) + $nestedObjectDelimeter + key) : key;
  592. if(path.length && key === prevKey){
  593. // Create shortcut path (foo.bar == foo.bar.bar)
  594. keyWithShortPath = '' + path.join($nestedObjectDelimeter);
  595. // Link it to original path
  596. result[keyWithShortPath] = '@:' + keyWithPath;
  597. }
  598. result[keyWithPath] = val;
  599. }
  600. }
  601. return result;
  602. };
  603. flatObject.displayName = 'flatObject';
  604. /**
  605. * @ngdoc function
  606. * @name pascalprecht.translate.$translateProvider#addInterpolation
  607. * @methodOf pascalprecht.translate.$translateProvider
  608. *
  609. * @description
  610. * Adds interpolation services to angular-translate, so it can manage them.
  611. *
  612. * @param {object} factory Interpolation service factory
  613. */
  614. this.addInterpolation = function (factory) {
  615. $interpolatorFactories.push(factory);
  616. return this;
  617. };
  618. /**
  619. * @ngdoc function
  620. * @name pascalprecht.translate.$translateProvider#useMessageFormatInterpolation
  621. * @methodOf pascalprecht.translate.$translateProvider
  622. *
  623. * @description
  624. * Tells angular-translate to use interpolation functionality of messageformat.js.
  625. * This is useful when having high level pluralization and gender selection.
  626. */
  627. this.useMessageFormatInterpolation = function () {
  628. return this.useInterpolation('$translateMessageFormatInterpolation');
  629. };
  630. /**
  631. * @ngdoc function
  632. * @name pascalprecht.translate.$translateProvider#useInterpolation
  633. * @methodOf pascalprecht.translate.$translateProvider
  634. *
  635. * @description
  636. * Tells angular-translate which interpolation style to use as default, application-wide.
  637. * Simply pass a factory/service name. The interpolation service has to implement
  638. * the correct interface.
  639. *
  640. * @param {string} factory Interpolation service name.
  641. */
  642. this.useInterpolation = function (factory) {
  643. $interpolationFactory = factory;
  644. return this;
  645. };
  646. /**
  647. * @ngdoc function
  648. * @name pascalprecht.translate.$translateProvider#useSanitizeStrategy
  649. * @methodOf pascalprecht.translate.$translateProvider
  650. *
  651. * @description
  652. * Simply sets a sanitation strategy type.
  653. *
  654. * @param {string} value Strategy type.
  655. */
  656. this.useSanitizeValueStrategy = function (value) {
  657. $translateSanitizationProvider.useStrategy(value);
  658. return this;
  659. };
  660. /**
  661. * @ngdoc function
  662. * @name pascalprecht.translate.$translateProvider#preferredLanguage
  663. * @methodOf pascalprecht.translate.$translateProvider
  664. *
  665. * @description
  666. * Tells the module which of the registered translation tables to use for translation
  667. * at initial startup by passing a language key. Similar to `$translateProvider#use`
  668. * only that it says which language to **prefer**.
  669. *
  670. * @param {string} langKey A language key.
  671. */
  672. this.preferredLanguage = function(langKey) {
  673. if (langKey) {
  674. setupPreferredLanguage(langKey);
  675. return this;
  676. }
  677. return $preferredLanguage;
  678. };
  679. var setupPreferredLanguage = function (langKey) {
  680. if (langKey) {
  681. $preferredLanguage = langKey;
  682. }
  683. return $preferredLanguage;
  684. };
  685. /**
  686. * @ngdoc function
  687. * @name pascalprecht.translate.$translateProvider#translationNotFoundIndicator
  688. * @methodOf pascalprecht.translate.$translateProvider
  689. *
  690. * @description
  691. * Sets an indicator which is used when a translation isn't found. E.g. when
  692. * setting the indicator as 'X' and one tries to translate a translation id
  693. * called `NOT_FOUND`, this will result in `X NOT_FOUND X`.
  694. *
  695. * Internally this methods sets a left indicator and a right indicator using
  696. * `$translateProvider.translationNotFoundIndicatorLeft()` and
  697. * `$translateProvider.translationNotFoundIndicatorRight()`.
  698. *
  699. * **Note**: These methods automatically add a whitespace between the indicators
  700. * and the translation id.
  701. *
  702. * @param {string} indicator An indicator, could be any string.
  703. */
  704. this.translationNotFoundIndicator = function (indicator) {
  705. this.translationNotFoundIndicatorLeft(indicator);
  706. this.translationNotFoundIndicatorRight(indicator);
  707. return this;
  708. };
  709. /**
  710. * ngdoc function
  711. * @name pascalprecht.translate.$translateProvider#translationNotFoundIndicatorLeft
  712. * @methodOf pascalprecht.translate.$translateProvider
  713. *
  714. * @description
  715. * Sets an indicator which is used when a translation isn't found left to the
  716. * translation id.
  717. *
  718. * @param {string} indicator An indicator.
  719. */
  720. this.translationNotFoundIndicatorLeft = function (indicator) {
  721. if (!indicator) {
  722. return $notFoundIndicatorLeft;
  723. }
  724. $notFoundIndicatorLeft = indicator;
  725. return this;
  726. };
  727. /**
  728. * ngdoc function
  729. * @name pascalprecht.translate.$translateProvider#translationNotFoundIndicatorLeft
  730. * @methodOf pascalprecht.translate.$translateProvider
  731. *
  732. * @description
  733. * Sets an indicator which is used when a translation isn't found right to the
  734. * translation id.
  735. *
  736. * @param {string} indicator An indicator.
  737. */
  738. this.translationNotFoundIndicatorRight = function (indicator) {
  739. if (!indicator) {
  740. return $notFoundIndicatorRight;
  741. }
  742. $notFoundIndicatorRight = indicator;
  743. return this;
  744. };
  745. /**
  746. * @ngdoc function
  747. * @name pascalprecht.translate.$translateProvider#fallbackLanguage
  748. * @methodOf pascalprecht.translate.$translateProvider
  749. *
  750. * @description
  751. * Tells the module which of the registered translation tables to use when missing translations
  752. * at initial startup by passing a language key. Similar to `$translateProvider#use`
  753. * only that it says which language to **fallback**.
  754. *
  755. * @param {string||array} langKey A language key.
  756. *
  757. */
  758. this.fallbackLanguage = function (langKey) {
  759. fallbackStack(langKey);
  760. return this;
  761. };
  762. var fallbackStack = function (langKey) {
  763. if (langKey) {
  764. if (angular.isString(langKey)) {
  765. $fallbackWasString = true;
  766. $fallbackLanguage = [ langKey ];
  767. } else if (angular.isArray(langKey)) {
  768. $fallbackWasString = false;
  769. $fallbackLanguage = langKey;
  770. }
  771. if (angular.isString($preferredLanguage) && indexOf($fallbackLanguage, $preferredLanguage) < 0) {
  772. $fallbackLanguage.push($preferredLanguage);
  773. }
  774. return this;
  775. } else {
  776. if ($fallbackWasString) {
  777. return $fallbackLanguage[0];
  778. } else {
  779. return $fallbackLanguage;
  780. }
  781. }
  782. };
  783. /**
  784. * @ngdoc function
  785. * @name pascalprecht.translate.$translateProvider#use
  786. * @methodOf pascalprecht.translate.$translateProvider
  787. *
  788. * @description
  789. * Set which translation table to use for translation by given language key. When
  790. * trying to 'use' a language which isn't provided, it'll throw an error.
  791. *
  792. * You actually don't have to use this method since `$translateProvider#preferredLanguage`
  793. * does the job too.
  794. *
  795. * @param {string} langKey A language key.
  796. */
  797. this.use = function (langKey) {
  798. if (langKey) {
  799. if (!$translationTable[langKey] && (!$loaderFactory)) {
  800. // only throw an error, when not loading translation data asynchronously
  801. throw new Error('$translateProvider couldn\'t find translationTable for langKey: \'' + langKey + '\'');
  802. }
  803. $uses = langKey;
  804. return this;
  805. }
  806. return $uses;
  807. };
  808. /**
  809. * @ngdoc function
  810. * @name pascalprecht.translate.$translateProvider#storageKey
  811. * @methodOf pascalprecht.translate.$translateProvider
  812. *
  813. * @description
  814. * Tells the module which key must represent the choosed language by a user in the storage.
  815. *
  816. * @param {string} key A key for the storage.
  817. */
  818. var storageKey = function(key) {
  819. if (!key) {
  820. if ($storagePrefix) {
  821. return $storagePrefix + $storageKey;
  822. }
  823. return $storageKey;
  824. }
  825. $storageKey = key;
  826. return this;
  827. };
  828. this.storageKey = storageKey;
  829. /**
  830. * @ngdoc function
  831. * @name pascalprecht.translate.$translateProvider#useUrlLoader
  832. * @methodOf pascalprecht.translate.$translateProvider
  833. *
  834. * @description
  835. * Tells angular-translate to use `$translateUrlLoader` extension service as loader.
  836. *
  837. * @param {string} url Url
  838. * @param {Object=} options Optional configuration object
  839. */
  840. this.useUrlLoader = function (url, options) {
  841. return this.useLoader('$translateUrlLoader', angular.extend({ url: url }, options));
  842. };
  843. /**
  844. * @ngdoc function
  845. * @name pascalprecht.translate.$translateProvider#useStaticFilesLoader
  846. * @methodOf pascalprecht.translate.$translateProvider
  847. *
  848. * @description
  849. * Tells angular-translate to use `$translateStaticFilesLoader` extension service as loader.
  850. *
  851. * @param {Object=} options Optional configuration object
  852. */
  853. this.useStaticFilesLoader = function (options) {
  854. return this.useLoader('$translateStaticFilesLoader', options);
  855. };
  856. /**
  857. * @ngdoc function
  858. * @name pascalprecht.translate.$translateProvider#useLoader
  859. * @methodOf pascalprecht.translate.$translateProvider
  860. *
  861. * @description
  862. * Tells angular-translate to use any other service as loader.
  863. *
  864. * @param {string} loaderFactory Factory name to use
  865. * @param {Object=} options Optional configuration object
  866. */
  867. this.useLoader = function (loaderFactory, options) {
  868. $loaderFactory = loaderFactory;
  869. $loaderOptions = options || {};
  870. return this;
  871. };
  872. /**
  873. * @ngdoc function
  874. * @name pascalprecht.translate.$translateProvider#useLocalStorage
  875. * @methodOf pascalprecht.translate.$translateProvider
  876. *
  877. * @description
  878. * Tells angular-translate to use `$translateLocalStorage` service as storage layer.
  879. *
  880. */
  881. this.useLocalStorage = function () {
  882. return this.useStorage('$translateLocalStorage');
  883. };
  884. /**
  885. * @ngdoc function
  886. * @name pascalprecht.translate.$translateProvider#useCookieStorage
  887. * @methodOf pascalprecht.translate.$translateProvider
  888. *
  889. * @description
  890. * Tells angular-translate to use `$translateCookieStorage` service as storage layer.
  891. */
  892. this.useCookieStorage = function () {
  893. return this.useStorage('$translateCookieStorage');
  894. };
  895. /**
  896. * @ngdoc function
  897. * @name pascalprecht.translate.$translateProvider#useStorage
  898. * @methodOf pascalprecht.translate.$translateProvider
  899. *
  900. * @description
  901. * Tells angular-translate to use custom service as storage layer.
  902. */
  903. this.useStorage = function (storageFactory) {
  904. $storageFactory = storageFactory;
  905. return this;
  906. };
  907. /**
  908. * @ngdoc function
  909. * @name pascalprecht.translate.$translateProvider#storagePrefix
  910. * @methodOf pascalprecht.translate.$translateProvider
  911. *
  912. * @description
  913. * Sets prefix for storage key.
  914. *
  915. * @param {string} prefix Storage key prefix
  916. */
  917. this.storagePrefix = function (prefix) {
  918. if (!prefix) {
  919. return prefix;
  920. }
  921. $storagePrefix = prefix;
  922. return this;
  923. };
  924. /**
  925. * @ngdoc function
  926. * @name pascalprecht.translate.$translateProvider#useMissingTranslationHandlerLog
  927. * @methodOf pascalprecht.translate.$translateProvider
  928. *
  929. * @description
  930. * Tells angular-translate to use built-in log handler when trying to translate
  931. * a translation Id which doesn't exist.
  932. *
  933. * This is actually a shortcut method for `useMissingTranslationHandler()`.
  934. *
  935. */
  936. this.useMissingTranslationHandlerLog = function () {
  937. return this.useMissingTranslationHandler('$translateMissingTranslationHandlerLog');
  938. };
  939. /**
  940. * @ngdoc function
  941. * @name pascalprecht.translate.$translateProvider#useMissingTranslationHandler
  942. * @methodOf pascalprecht.translate.$translateProvider
  943. *
  944. * @description
  945. * Expects a factory name which later gets instantiated with `$injector`.
  946. * This method can be used to tell angular-translate to use a custom
  947. * missingTranslationHandler. Just build a factory which returns a function
  948. * and expects a translation id as argument.
  949. *
  950. * Example:
  951. * <pre>
  952. * app.config(function ($translateProvider) {
  953. * $translateProvider.useMissingTranslationHandler('customHandler');
  954. * });
  955. *
  956. * app.factory('customHandler', function (dep1, dep2) {
  957. * return function (translationId) {
  958. * // something with translationId and dep1 and dep2
  959. * };
  960. * });
  961. * </pre>
  962. *
  963. * @param {string} factory Factory name
  964. */
  965. this.useMissingTranslationHandler = function (factory) {
  966. $missingTranslationHandlerFactory = factory;
  967. return this;
  968. };
  969. /**
  970. * @ngdoc function
  971. * @name pascalprecht.translate.$translateProvider#usePostCompiling
  972. * @methodOf pascalprecht.translate.$translateProvider
  973. *
  974. * @description
  975. * If post compiling is enabled, all translated values will be processed
  976. * again with AngularJS' $compile.
  977. *
  978. * Example:
  979. * <pre>
  980. * app.config(function ($translateProvider) {
  981. * $translateProvider.usePostCompiling(true);
  982. * });
  983. * </pre>
  984. *
  985. * @param {string} factory Factory name
  986. */
  987. this.usePostCompiling = function (value) {
  988. $postCompilingEnabled = !(!value);
  989. return this;
  990. };
  991. /**
  992. * @ngdoc function
  993. * @name pascalprecht.translate.$translateProvider#forceAsyncReload
  994. * @methodOf pascalprecht.translate.$translateProvider
  995. *
  996. * @description
  997. * If force async reload is enabled, async loader will always be called
  998. * even if $translationTable already contains the language key, adding
  999. * possible new entries to the $translationTable.
  1000. *
  1001. * Example:
  1002. * <pre>
  1003. * app.config(function ($translateProvider) {
  1004. * $translateProvider.forceAsyncReload(true);
  1005. * });
  1006. * </pre>
  1007. *
  1008. * @param {boolean} value - valid values are true or false
  1009. */
  1010. this.forceAsyncReload = function (value) {
  1011. $forceAsyncReloadEnabled = !(!value);
  1012. return this;
  1013. };
  1014. /**
  1015. * @ngdoc function
  1016. * @name pascalprecht.translate.$translateProvider#uniformLanguageTag
  1017. * @methodOf pascalprecht.translate.$translateProvider
  1018. *
  1019. * @description
  1020. * Tells angular-translate which language tag should be used as a result when determining
  1021. * the current browser language.
  1022. *
  1023. * This setting must be set before invoking {@link pascalprecht.translate.$translateProvider#methods_determinePreferredLanguage determinePreferredLanguage()}.
  1024. *
  1025. * <pre>
  1026. * $translateProvider
  1027. * .uniformLanguageTag('bcp47')
  1028. * .determinePreferredLanguage()
  1029. * </pre>
  1030. *
  1031. * The resolver currently supports:
  1032. * * default
  1033. * (traditionally: hyphens will be converted into underscores, i.e. en-US => en_US)
  1034. * en-US => en_US
  1035. * en_US => en_US
  1036. * en-us => en_us
  1037. * * java
  1038. * like default, but the second part will be always in uppercase
  1039. * en-US => en_US
  1040. * en_US => en_US
  1041. * en-us => en_US
  1042. * * BCP 47 (RFC 4646 & 4647)
  1043. * en-US => en-US
  1044. * en_US => en-US
  1045. * en-us => en-US
  1046. *
  1047. * See also:
  1048. * * http://en.wikipedia.org/wiki/IETF_language_tag
  1049. * * http://www.w3.org/International/core/langtags/
  1050. * * http://tools.ietf.org/html/bcp47
  1051. *
  1052. * @param {string|object} options - options (or standard)
  1053. * @param {string} options.standard - valid values are 'default', 'bcp47', 'java'
  1054. */
  1055. this.uniformLanguageTag = function (options) {
  1056. if (!options) {
  1057. options = {};
  1058. } else if (angular.isString(options)) {
  1059. options = {
  1060. standard: options
  1061. };
  1062. }
  1063. uniformLanguageTagResolver = options.standard;
  1064. return this;
  1065. };
  1066. /**
  1067. * @ngdoc function
  1068. * @name pascalprecht.translate.$translateProvider#determinePreferredLanguage
  1069. * @methodOf pascalprecht.translate.$translateProvider
  1070. *
  1071. * @description
  1072. * Tells angular-translate to try to determine on its own which language key
  1073. * to set as preferred language. When `fn` is given, angular-translate uses it
  1074. * to determine a language key, otherwise it uses the built-in `getLocale()`
  1075. * method.
  1076. *
  1077. * The `getLocale()` returns a language key in the format `[lang]_[country]` or
  1078. * `[lang]` depending on what the browser provides.
  1079. *
  1080. * Use this method at your own risk, since not all browsers return a valid
  1081. * locale (see {@link pascalprecht.translate.$translateProvider#methods_uniformLanguageTag uniformLanguageTag()}).
  1082. *
  1083. * @param {Function=} fn Function to determine a browser's locale
  1084. */
  1085. this.determinePreferredLanguage = function (fn) {
  1086. var locale = (fn && angular.isFunction(fn)) ? fn() : getLocale();
  1087. if (!$availableLanguageKeys.length) {
  1088. $preferredLanguage = locale;
  1089. } else {
  1090. $preferredLanguage = negotiateLocale(locale) || locale;
  1091. }
  1092. return this;
  1093. };
  1094. /**
  1095. * @ngdoc function
  1096. * @name pascalprecht.translate.$translateProvider#registerAvailableLanguageKeys
  1097. * @methodOf pascalprecht.translate.$translateProvider
  1098. *
  1099. * @description
  1100. * Registers a set of language keys the app will work with. Use this method in
  1101. * combination with
  1102. * {@link pascalprecht.translate.$translateProvider#determinePreferredLanguage determinePreferredLanguage}.
  1103. * When available languages keys are registered, angular-translate
  1104. * tries to find the best fitting language key depending on the browsers locale,
  1105. * considering your language key convention.
  1106. *
  1107. * @param {object} languageKeys Array of language keys the your app will use
  1108. * @param {object=} aliases Alias map.
  1109. */
  1110. this.registerAvailableLanguageKeys = function (languageKeys, aliases) {
  1111. if (languageKeys) {
  1112. $availableLanguageKeys = languageKeys;
  1113. if (aliases) {
  1114. $languageKeyAliases = aliases;
  1115. }
  1116. return this;
  1117. }
  1118. return $availableLanguageKeys;
  1119. };
  1120. /**
  1121. * @ngdoc function
  1122. * @name pascalprecht.translate.$translateProvider#useLoaderCache
  1123. * @methodOf pascalprecht.translate.$translateProvider
  1124. *
  1125. * @description
  1126. * Registers a cache for internal $http based loaders.
  1127. * {@link pascalprecht.translate.$translationCache $translationCache}.
  1128. * When false the cache will be disabled (default). When true or undefined
  1129. * the cache will be a default (see $cacheFactory). When an object it will
  1130. * be treat as a cache object itself: the usage is $http({cache: cache})
  1131. *
  1132. * @param {object} cache boolean, string or cache-object
  1133. */
  1134. this.useLoaderCache = function (cache) {
  1135. if (cache === false) {
  1136. // disable cache
  1137. loaderCache = undefined;
  1138. } else if (cache === true) {
  1139. // enable cache using AJS defaults
  1140. loaderCache = true;
  1141. } else if (typeof(cache) === 'undefined') {
  1142. // enable cache using default
  1143. loaderCache = '$translationCache';
  1144. } else if (cache) {
  1145. // enable cache using given one (see $cacheFactory)
  1146. loaderCache = cache;
  1147. }
  1148. return this;
  1149. };
  1150. /**
  1151. * @ngdoc function
  1152. * @name pascalprecht.translate.$translateProvider#directivePriority
  1153. * @methodOf pascalprecht.translate.$translateProvider
  1154. *
  1155. * @description
  1156. * Sets the default priority of the translate directive. The standard value is `0`.
  1157. * Calling this function without an argument will return the current value.
  1158. *
  1159. * @param {number} priority for the translate-directive
  1160. */
  1161. this.directivePriority = function (priority) {
  1162. if (priority === undefined) {
  1163. // getter
  1164. return directivePriority;
  1165. } else {
  1166. // setter with chaining
  1167. directivePriority = priority;
  1168. return this;
  1169. }
  1170. };
  1171. /**
  1172. * @ngdoc function
  1173. * @name pascalprecht.translate.$translateProvider#statefulFilter
  1174. * @methodOf pascalprecht.translate.$translateProvider
  1175. *
  1176. * @description
  1177. * Since AngularJS 1.3, filters which are not stateless (depending at the scope)
  1178. * have to explicit define this behavior.
  1179. * Sets whether the translate filter should be stateful or stateless. The standard value is `true`
  1180. * meaning being stateful.
  1181. * Calling this function without an argument will return the current value.
  1182. *
  1183. * @param {boolean} state - defines the state of the filter
  1184. */
  1185. this.statefulFilter = function (state) {
  1186. if (state === undefined) {
  1187. // getter
  1188. return statefulFilter;
  1189. } else {
  1190. // setter with chaining
  1191. statefulFilter = state;
  1192. return this;
  1193. }
  1194. };
  1195. /**
  1196. * @ngdoc object
  1197. * @name pascalprecht.translate.$translate
  1198. * @requires $interpolate
  1199. * @requires $log
  1200. * @requires $rootScope
  1201. * @requires $q
  1202. *
  1203. * @description
  1204. * The `$translate` service is the actual core of angular-translate. It expects a translation id
  1205. * and optional interpolate parameters to translate contents.
  1206. *
  1207. * <pre>
  1208. * $translate('HEADLINE_TEXT').then(function (translation) {
  1209. * $scope.translatedText = translation;
  1210. * });
  1211. * </pre>
  1212. *
  1213. * @param {string|array} translationId A token which represents a translation id
  1214. * This can be optionally an array of translation ids which
  1215. * results that the function returns an object where each key
  1216. * is the translation id and the value the translation.
  1217. * @param {object=} interpolateParams An object hash for dynamic values
  1218. * @param {string} interpolationId The id of the interpolation to use
  1219. * @param {string} forceLanguage A language to be used instead of the current language
  1220. * @returns {object} promise
  1221. */
  1222. this.$get = [
  1223. '$log',
  1224. '$injector',
  1225. '$rootScope',
  1226. '$q',
  1227. function ($log, $injector, $rootScope, $q) {
  1228. var Storage,
  1229. defaultInterpolator = $injector.get($interpolationFactory || '$translateDefaultInterpolation'),
  1230. pendingLoader = false,
  1231. interpolatorHashMap = {},
  1232. langPromises = {},
  1233. fallbackIndex,
  1234. startFallbackIteration;
  1235. var $translate = function (translationId, interpolateParams, interpolationId, defaultTranslationText, forceLanguage) {
  1236. var uses = (forceLanguage && forceLanguage !== $uses) ? // we don't want to re-negotiate $uses
  1237. (negotiateLocale(forceLanguage) || forceLanguage) : $uses;
  1238. // Duck detection: If the first argument is an array, a bunch of translations was requested.
  1239. // The result is an object.
  1240. if (angular.isArray(translationId)) {
  1241. // Inspired by Q.allSettled by Kris Kowal
  1242. // https://github.com/kriskowal/q/blob/b0fa72980717dc202ffc3cbf03b936e10ebbb9d7/q.js#L1553-1563
  1243. // This transforms all promises regardless resolved or rejected
  1244. var translateAll = function (translationIds) {
  1245. var results = {}; // storing the actual results
  1246. var promises = []; // promises to wait for
  1247. // Wraps the promise a) being always resolved and b) storing the link id->value
  1248. var translate = function (translationId) {
  1249. var deferred = $q.defer();
  1250. var regardless = function (value) {
  1251. results[translationId] = value;
  1252. deferred.resolve([translationId, value]);
  1253. };
  1254. // we don't care whether the promise was resolved or rejected; just store the values
  1255. $translate(translationId, interpolateParams, interpolationId, defaultTranslationText, forceLanguage).then(regardless, regardless);
  1256. return deferred.promise;
  1257. };
  1258. for (var i = 0, c = translationIds.length; i < c; i++) {
  1259. promises.push(translate(translationIds[i]));
  1260. }
  1261. // wait for all (including storing to results)
  1262. return $q.all(promises).then(function () {
  1263. // return the results
  1264. return results;
  1265. });
  1266. };
  1267. return translateAll(translationId);
  1268. }
  1269. var deferred = $q.defer();
  1270. // trim off any whitespace
  1271. if (translationId) {
  1272. translationId = trim.apply(translationId);
  1273. }
  1274. var promiseToWaitFor = (function () {
  1275. var promise = $preferredLanguage ?
  1276. langPromises[$preferredLanguage] :
  1277. langPromises[uses];
  1278. fallbackIndex = 0;
  1279. if ($storageFactory && !promise) {
  1280. // looks like there's no pending promise for $preferredLanguage or
  1281. // $uses. Maybe there's one pending for a language that comes from
  1282. // storage.
  1283. var langKey = Storage.get($storageKey);
  1284. promise = langPromises[langKey];
  1285. if ($fallbackLanguage && $fallbackLanguage.length) {
  1286. var index = indexOf($fallbackLanguage, langKey);
  1287. // maybe the language from storage is also defined as fallback language
  1288. // we increase the fallback language index to not search in that language
  1289. // as fallback, since it's probably the first used language
  1290. // in that case the index starts after the first element
  1291. fallbackIndex = (index === 0) ? 1 : 0;
  1292. // but we can make sure to ALWAYS fallback to preferred language at least
  1293. if (indexOf($fallbackLanguage, $preferredLanguage) < 0) {
  1294. $fallbackLanguage.push($preferredLanguage);
  1295. }
  1296. }
  1297. }
  1298. return promise;
  1299. }());
  1300. if (!promiseToWaitFor) {
  1301. // no promise to wait for? okay. Then there's no loader registered
  1302. // nor is a one pending for language that comes from storage.
  1303. // We can just translate.
  1304. determineTranslation(translationId, interpolateParams, interpolationId, defaultTranslationText, uses).then(deferred.resolve, deferred.reject);
  1305. } else {
  1306. var promiseResolved = function () {
  1307. // $uses may have changed while waiting
  1308. if (!forceLanguage) {
  1309. uses = $uses;
  1310. }
  1311. determineTranslation(translationId, interpolateParams, interpolationId, defaultTranslationText, uses).then(deferred.resolve, deferred.reject);
  1312. };
  1313. promiseResolved.displayName = 'promiseResolved';
  1314. promiseToWaitFor['finally'](promiseResolved, deferred.reject);
  1315. }
  1316. return deferred.promise;
  1317. };
  1318. /**
  1319. * @name applyNotFoundIndicators
  1320. * @private
  1321. *
  1322. * @description
  1323. * Applies not fount indicators to given translation id, if needed.
  1324. * This function gets only executed, if a translation id doesn't exist,
  1325. * which is why a translation id is expected as argument.
  1326. *
  1327. * @param {string} translationId Translation id.
  1328. * @returns {string} Same as given translation id but applied with not found
  1329. * indicators.
  1330. */
  1331. var applyNotFoundIndicators = function (translationId) {
  1332. // applying notFoundIndicators
  1333. if ($notFoundIndicatorLeft) {
  1334. translationId = [$notFoundIndicatorLeft, translationId].join(' ');
  1335. }
  1336. if ($notFoundIndicatorRight) {
  1337. translationId = [translationId, $notFoundIndicatorRight].join(' ');
  1338. }
  1339. return translationId;
  1340. };
  1341. /**
  1342. * @name useLanguage
  1343. * @private
  1344. *
  1345. * @description
  1346. * Makes actual use of a language by setting a given language key as used
  1347. * language and informs registered interpolators to also use the given
  1348. * key as locale.
  1349. *
  1350. * @param {key} Locale key.
  1351. */
  1352. var useLanguage = function (key) {
  1353. $uses = key;
  1354. // make sure to store new language key before triggering success event
  1355. if ($storageFactory) {
  1356. Storage.put($translate.storageKey(), $uses);
  1357. }
  1358. $rootScope.$emit('$translateChangeSuccess', {language: key});
  1359. // inform default interpolator
  1360. defaultInterpolator.setLocale($uses);
  1361. var eachInterpolator = function (interpolator, id) {
  1362. interpolatorHashMap[id].setLocale($uses);
  1363. };
  1364. eachInterpolator.displayName = 'eachInterpolatorLocaleSetter';
  1365. // inform all others too!
  1366. angular.forEach(interpolatorHashMap, eachInterpolator);
  1367. $rootScope.$emit('$translateChangeEnd', {language: key});
  1368. };
  1369. /**
  1370. * @name loadAsync
  1371. * @private
  1372. *
  1373. * @description
  1374. * Kicks of registered async loader using `$injector` and applies existing
  1375. * loader options. When resolved, it updates translation tables accordingly
  1376. * or rejects with given language key.
  1377. *
  1378. * @param {string} key Language key.
  1379. * @return {Promise} A promise.
  1380. */
  1381. var loadAsync = function (key) {
  1382. if (!key) {
  1383. throw 'No language key specified for loading.';
  1384. }
  1385. var deferred = $q.defer();
  1386. $rootScope.$emit('$translateLoadingStart', {language: key});
  1387. pendingLoader = true;
  1388. var cache = loaderCache;
  1389. if (typeof(cache) === 'string') {
  1390. // getting on-demand instance of loader
  1391. cache = $injector.get(cache);
  1392. }
  1393. var loaderOptions = angular.extend({}, $loaderOptions, {
  1394. key: key,
  1395. $http: angular.extend({}, {
  1396. cache: cache
  1397. }, $loaderOptions.$http)
  1398. });
  1399. var onLoaderSuccess = function (data) {
  1400. var translationTable = {};
  1401. $rootScope.$emit('$translateLoadingSuccess', {language: key});
  1402. if (angular.isArray(data)) {
  1403. angular.forEach(data, function (table) {
  1404. angular.extend(translationTable, flatObject(table));
  1405. });
  1406. } else {
  1407. angular.extend(translationTable, flatObject(data));
  1408. }
  1409. pendingLoader = false;
  1410. deferred.resolve({
  1411. key: key,
  1412. table: translationTable
  1413. });
  1414. $rootScope.$emit('$translateLoadingEnd', {language: key});
  1415. };
  1416. onLoaderSuccess.displayName = 'onLoaderSuccess';
  1417. var onLoaderError = function (key) {
  1418. $rootScope.$emit('$translateLoadingError', {language: key});
  1419. deferred.reject(key);
  1420. $rootScope.$emit('$translateLoadingEnd', {language: key});
  1421. };
  1422. onLoaderError.displayName = 'onLoaderError';
  1423. $injector.get($loaderFactory)(loaderOptions)
  1424. .then(onLoaderSuccess, onLoaderError);
  1425. return deferred.promise;
  1426. };
  1427. if ($storageFactory) {
  1428. Storage = $injector.get($storageFactory);
  1429. if (!Storage.get || !Storage.put) {
  1430. throw new Error('Couldn\'t use storage \'' + $storageFactory + '\', missing get() or put() method!');
  1431. }
  1432. }
  1433. // if we have additional interpolations that were added via
  1434. // $translateProvider.addInterpolation(), we have to map'em
  1435. if ($interpolatorFactories.length) {
  1436. var eachInterpolationFactory = function (interpolatorFactory) {
  1437. var interpolator = $injector.get(interpolatorFactory);
  1438. // setting initial locale for each interpolation service
  1439. interpolator.setLocale($preferredLanguage || $uses);
  1440. // make'em recognizable through id
  1441. interpolatorHashMap[interpolator.getInterpolationIdentifier()] = interpolator;
  1442. };
  1443. eachInterpolationFactory.displayName = 'interpolationFactoryAdder';
  1444. angular.forEach($interpolatorFactories, eachInterpolationFactory);
  1445. }
  1446. /**
  1447. * @name getTranslationTable
  1448. * @private
  1449. *
  1450. * @description
  1451. * Returns a promise that resolves to the translation table
  1452. * or is rejected if an error occurred.
  1453. *
  1454. * @param langKey
  1455. * @returns {Q.promise}
  1456. */
  1457. var getTranslationTable = function (langKey) {
  1458. var deferred = $q.defer();
  1459. if (Object.prototype.hasOwnProperty.call($translationTable, langKey)) {
  1460. deferred.resolve($translationTable[langKey]);
  1461. } else if (langPromises[langKey]) {
  1462. var onResolve = function (data) {
  1463. translations(data.key, data.table);
  1464. deferred.resolve(data.table);
  1465. };
  1466. onResolve.displayName = 'translationTableResolver';
  1467. langPromises[langKey].then(onResolve, deferred.reject);
  1468. } else {
  1469. deferred.reject();
  1470. }
  1471. return deferred.promise;
  1472. };
  1473. /**
  1474. * @name getFallbackTranslation
  1475. * @private
  1476. *
  1477. * @description
  1478. * Returns a promise that will resolve to the translation
  1479. * or be rejected if no translation was found for the language.
  1480. * This function is currently only used for fallback language translation.
  1481. *
  1482. * @param langKey The language to translate to.
  1483. * @param translationId
  1484. * @param interpolateParams
  1485. * @param Interpolator
  1486. * @returns {Q.promise}
  1487. */
  1488. var getFallbackTranslation = function (langKey, translationId, interpolateParams, Interpolator) {
  1489. var deferred = $q.defer();
  1490. var onResolve = function (translationTable) {
  1491. if (Object.prototype.hasOwnProperty.call(translationTable, translationId)) {
  1492. Interpolator.setLocale(langKey);
  1493. var translation = translationTable[translationId];
  1494. if (translation.substr(0, 2) === '@:') {
  1495. getFallbackTranslation(langKey, translation.substr(2), interpolateParams, Interpolator)
  1496. .then(deferred.resolve, deferred.reject);
  1497. } else {
  1498. deferred.resolve(Interpolator.interpolate(translationTable[translationId], interpolateParams));
  1499. }
  1500. Interpolator.setLocale($uses);
  1501. } else {
  1502. deferred.reject();
  1503. }
  1504. };
  1505. onResolve.displayName = 'fallbackTranslationResolver';
  1506. getTranslationTable(langKey).then(onResolve, deferred.reject);
  1507. return deferred.promise;
  1508. };
  1509. /**
  1510. * @name getFallbackTranslationInstant
  1511. * @private
  1512. *
  1513. * @description
  1514. * Returns a translation
  1515. * This function is currently only used for fallback language translation.
  1516. *
  1517. * @param langKey The language to translate to.
  1518. * @param translationId
  1519. * @param interpolateParams
  1520. * @param Interpolator
  1521. * @returns {string} translation
  1522. */
  1523. var getFallbackTranslationInstant = function (langKey, translationId, interpolateParams, Interpolator) {
  1524. var result, translationTable = $translationTable[langKey];
  1525. if (translationTable && Object.prototype.hasOwnProperty.call(translationTable, translationId)) {
  1526. Interpolator.setLocale(langKey);
  1527. result = Interpolator.interpolate(translationTable[translationId], interpolateParams);
  1528. if (result.substr(0, 2) === '@:') {
  1529. return getFallbackTranslationInstant(langKey, result.substr(2), interpolateParams, Interpolator);
  1530. }
  1531. Interpolator.setLocale($uses);
  1532. }
  1533. return result;
  1534. };
  1535. /**
  1536. * @name translateByHandler
  1537. * @private
  1538. *
  1539. * Translate by missing translation handler.
  1540. *
  1541. * @param translationId
  1542. * @returns translation created by $missingTranslationHandler or translationId is $missingTranslationHandler is
  1543. * absent
  1544. */
  1545. var translateByHandler = function (translationId, interpolateParams) {
  1546. // If we have a handler factory - we might also call it here to determine if it provides
  1547. // a default text for a translationid that can't be found anywhere in our tables
  1548. if ($missingTranslationHandlerFactory) {
  1549. var resultString = $injector.get($missingTranslationHandlerFactory)(translationId, $uses, interpolateParams);
  1550. if (resultString !== undefined) {
  1551. return resultString;
  1552. } else {
  1553. return translationId;
  1554. }
  1555. } else {
  1556. return translationId;
  1557. }
  1558. };
  1559. /**
  1560. * @name resolveForFallbackLanguage
  1561. * @private
  1562. *
  1563. * Recursive helper function for fallbackTranslation that will sequentially look
  1564. * for a translation in the fallbackLanguages starting with fallbackLanguageIndex.
  1565. *
  1566. * @param fallbackLanguageIndex
  1567. * @param translationId
  1568. * @param interpolateParams
  1569. * @param Interpolator
  1570. * @returns {Q.promise} Promise that will resolve to the translation.
  1571. */
  1572. var resolveForFallbackLanguage = function (fallbackLanguageIndex, translationId, interpolateParams, Interpolator, defaultTranslationText) {
  1573. var deferred = $q.defer();
  1574. if (fallbackLanguageIndex < $fallbackLanguage.length) {
  1575. var langKey = $fallbackLanguage[fallbackLanguageIndex];
  1576. getFallbackTranslation(langKey, translationId, interpolateParams, Interpolator).then(
  1577. deferred.resolve,
  1578. function () {
  1579. // Look in the next fallback language for a translation.
  1580. // It delays the resolving by passing another promise to resolve.
  1581. resolveForFallbackLanguage(fallbackLanguageIndex + 1, translationId, interpolateParams, Interpolator, defaultTranslationText).then(deferred.resolve);
  1582. }
  1583. );
  1584. } else {
  1585. // No translation found in any fallback language
  1586. // if a default translation text is set in the directive, then return this as a result
  1587. if (defaultTranslationText) {
  1588. deferred.resolve(defaultTranslationText);
  1589. } else {
  1590. // if no default translation is set and an error handler is defined, send it to the handler
  1591. // and then return the result
  1592. deferred.resolve(translateByHandler(translationId, interpolateParams));
  1593. }
  1594. }
  1595. return deferred.promise;
  1596. };
  1597. /**
  1598. * @name resolveForFallbackLanguageInstant
  1599. * @private
  1600. *
  1601. * Recursive helper function for fallbackTranslation that will sequentially look
  1602. * for a translation in the fallbackLanguages starting with fallbackLanguageIndex.
  1603. *
  1604. * @param fallbackLanguageIndex
  1605. * @param translationId
  1606. * @param interpolateParams
  1607. * @param Interpolator
  1608. * @returns {string} translation
  1609. */
  1610. var resolveForFallbackLanguageInstant = function (fallbackLanguageIndex, translationId, interpolateParams, Interpolator) {
  1611. var result;
  1612. if (fallbackLanguageIndex < $fallbackLanguage.length) {
  1613. var langKey = $fallbackLanguage[fallbackLanguageIndex];
  1614. result = getFallbackTranslationInstant(langKey, translationId, interpolateParams, Interpolator);
  1615. if (!result) {
  1616. result = resolveForFallbackLanguageInstant(fallbackLanguageIndex + 1, translationId, interpolateParams, Interpolator);
  1617. }
  1618. }
  1619. return result;
  1620. };
  1621. /**
  1622. * Translates with the usage of the fallback languages.
  1623. *
  1624. * @param translationId
  1625. * @param interpolateParams
  1626. * @param Interpolator
  1627. * @returns {Q.promise} Promise, that resolves to the translation.
  1628. */
  1629. var fallbackTranslation = function (translationId, interpolateParams, Interpolator, defaultTranslationText) {
  1630. // Start with the fallbackLanguage with index 0
  1631. return resolveForFallbackLanguage((startFallbackIteration>0 ? startFallbackIteration : fallbackIndex), translationId, interpolateParams, Interpolator, defaultTranslationText);
  1632. };
  1633. /**
  1634. * Translates with the usage of the fallback languages.
  1635. *
  1636. * @param translationId
  1637. * @param interpolateParams
  1638. * @param Interpolator
  1639. * @returns {String} translation
  1640. */
  1641. var fallbackTranslationInstant = function (translationId, interpolateParams, Interpolator) {
  1642. // Start with the fallbackLanguage with index 0
  1643. return resolveForFallbackLanguageInstant((startFallbackIteration>0 ? startFallbackIteration : fallbackIndex), translationId, interpolateParams, Interpolator);
  1644. };
  1645. var determineTranslation = function (translationId, interpolateParams, interpolationId, defaultTranslationText, uses) {
  1646. var deferred = $q.defer();
  1647. var table = uses ? $translationTable[uses] : $translationTable,
  1648. Interpolator = (interpolationId) ? interpolatorHashMap[interpolationId] : defaultInterpolator;
  1649. // if the translation id exists, we can just interpolate it
  1650. if (table && Object.prototype.hasOwnProperty.call(table, translationId)) {
  1651. var translation = table[translationId];
  1652. // If using link, rerun $translate with linked translationId and return it
  1653. if (translation.substr(0, 2) === '@:') {
  1654. $translate(translation.substr(2), interpolateParams, interpolationId, defaultTranslationText, uses)
  1655. .then(deferred.resolve, deferred.reject);
  1656. } else {
  1657. deferred.resolve(Interpolator.interpolate(translation, interpolateParams));
  1658. }
  1659. } else {
  1660. var missingTranslationHandlerTranslation;
  1661. // for logging purposes only (as in $translateMissingTranslationHandlerLog), value is not returned to promise
  1662. if ($missingTranslationHandlerFactory && !pendingLoader) {
  1663. missingTranslationHandlerTranslation = translateByHandler(translationId, interpolateParams);
  1664. }
  1665. // since we couldn't translate the inital requested translation id,
  1666. // we try it now with one or more fallback languages, if fallback language(s) is
  1667. // configured.
  1668. if (uses && $fallbackLanguage && $fallbackLanguage.length) {
  1669. fallbackTranslation(translationId, interpolateParams, Interpolator, defaultTranslationText)
  1670. .then(function (translation) {
  1671. deferred.resolve(translation);
  1672. }, function (_translationId) {
  1673. deferred.reject(applyNotFoundIndicators(_translationId));
  1674. });
  1675. } else if ($missingTranslationHandlerFactory && !pendingLoader && missingTranslationHandlerTranslation) {
  1676. // looks like the requested translation id doesn't exists.
  1677. // Now, if there is a registered handler for missing translations and no
  1678. // asyncLoader is pending, we execute the handler
  1679. if (defaultTranslationText) {
  1680. deferred.resolve(defaultTranslationText);
  1681. } else {
  1682. deferred.resolve(missingTranslationHandlerTranslation);
  1683. }
  1684. } else {
  1685. if (defaultTranslationText) {
  1686. deferred.resolve(defaultTranslationText);
  1687. } else {
  1688. deferred.reject(applyNotFoundIndicators(translationId));
  1689. }
  1690. }
  1691. }
  1692. return deferred.promise;
  1693. };
  1694. var determineTranslationInstant = function (translationId, interpolateParams, interpolationId, uses) {
  1695. var result, table = uses ? $translationTable[uses] : $translationTable,
  1696. Interpolator = defaultInterpolator;
  1697. // if the interpolation id exists use custom interpolator
  1698. if (interpolatorHashMap && Object.prototype.hasOwnProperty.call(interpolatorHashMap, interpolationId)) {
  1699. Interpolator = interpolatorHashMap[interpolationId];
  1700. }
  1701. // if the translation id exists, we can just interpolate it
  1702. if (table && Object.prototype.hasOwnProperty.call(table, translationId)) {
  1703. var translation = table[translationId];
  1704. // If using link, rerun $translate with linked translationId and return it
  1705. if (translation.substr(0, 2) === '@:') {
  1706. result = determineTranslationInstant(translation.substr(2), interpolateParams, interpolationId, uses);
  1707. } else {
  1708. result = Interpolator.interpolate(translation, interpolateParams);
  1709. }
  1710. } else {
  1711. var missingTranslationHandlerTranslation;
  1712. // for logging purposes only (as in $translateMissingTranslationHandlerLog), value is not returned to promise
  1713. if ($missingTranslationHandlerFactory && !pendingLoader) {
  1714. missingTranslationHandlerTranslation = translateByHandler(translationId, interpolateParams);
  1715. }
  1716. // since we couldn't translate the inital requested translation id,
  1717. // we try it now with one or more fallback languages, if fallback language(s) is
  1718. // configured.
  1719. if (uses && $fallbackLanguage && $fallbackLanguage.length) {
  1720. fallbackIndex = 0;
  1721. result = fallbackTranslationInstant(translationId, interpolateParams, Interpolator);
  1722. } else if ($missingTranslationHandlerFactory && !pendingLoader && missingTranslationHandlerTranslation) {
  1723. // looks like the requested translation id doesn't exists.
  1724. // Now, if there is a registered handler for missing translations and no
  1725. // asyncLoader is pending, we execute the handler
  1726. result = missingTranslationHandlerTranslation;
  1727. } else {
  1728. result = applyNotFoundIndicators(translationId);
  1729. }
  1730. }
  1731. return result;
  1732. };
  1733. var clearNextLangAndPromise = function(key) {
  1734. if ($nextLang === key) {
  1735. $nextLang = undefined;
  1736. }
  1737. langPromises[key] = undefined;
  1738. };
  1739. /**
  1740. * @ngdoc function
  1741. * @name pascalprecht.translate.$translate#preferredLanguage
  1742. * @methodOf pascalprecht.translate.$translate
  1743. *
  1744. * @description
  1745. * Returns the language key for the preferred language.
  1746. *
  1747. * @param {string} langKey language String or Array to be used as preferredLanguage (changing at runtime)
  1748. *
  1749. * @return {string} preferred language key
  1750. */
  1751. $translate.preferredLanguage = function (langKey) {
  1752. if(langKey) {
  1753. setupPreferredLanguage(langKey);
  1754. }
  1755. return $preferredLanguage;
  1756. };
  1757. /**
  1758. * @ngdoc function
  1759. * @name pascalprecht.translate.$translate#cloakClassName
  1760. * @methodOf pascalprecht.translate.$translate
  1761. *
  1762. * @description
  1763. * Returns the configured class name for `translate-cloak` directive.
  1764. *
  1765. * @return {string} cloakClassName
  1766. */
  1767. $translate.cloakClassName = function () {
  1768. return $cloakClassName;
  1769. };
  1770. /**
  1771. * @ngdoc function
  1772. * @name pascalprecht.translate.$translate#nestedObjectDelimeter
  1773. * @methodOf pascalprecht.translate.$translate
  1774. *
  1775. * @description
  1776. * Returns the configured delimiter for nested namespaces.
  1777. *
  1778. * @return {string} nestedObjectDelimeter
  1779. */
  1780. $translate.nestedObjectDelimeter = function () {
  1781. return $nestedObjectDelimeter;
  1782. };
  1783. /**
  1784. * @ngdoc function
  1785. * @name pascalprecht.translate.$translate#fallbackLanguage
  1786. * @methodOf pascalprecht.translate.$translate
  1787. *
  1788. * @description
  1789. * Returns the language key for the fallback languages or sets a new fallback stack.
  1790. *
  1791. * @param {string=} langKey language String or Array of fallback languages to be used (to change stack at runtime)
  1792. *
  1793. * @return {string||array} fallback language key
  1794. */
  1795. $translate.fallbackLanguage = function (langKey) {
  1796. if (langKey !== undefined && langKey !== null) {
  1797. fallbackStack(langKey);
  1798. // as we might have an async loader initiated and a new translation language might have been defined
  1799. // we need to add the promise to the stack also. So - iterate.
  1800. if ($loaderFactory) {
  1801. if ($fallbackLanguage && $fallbackLanguage.length) {
  1802. for (var i = 0, len = $fallbackLanguage.length; i < len; i++) {
  1803. if (!langPromises[$fallbackLanguage[i]]) {
  1804. langPromises[$fallbackLanguage[i]] = loadAsync($fallbackLanguage[i]);
  1805. }
  1806. }
  1807. }
  1808. }
  1809. $translate.use($translate.use());
  1810. }
  1811. if ($fallbackWasString) {
  1812. return $fallbackLanguage[0];
  1813. } else {
  1814. return $fallbackLanguage;
  1815. }
  1816. };
  1817. /**
  1818. * @ngdoc function
  1819. * @name pascalprecht.translate.$translate#useFallbackLanguage
  1820. * @methodOf pascalprecht.translate.$translate
  1821. *
  1822. * @description
  1823. * Sets the first key of the fallback language stack to be used for translation.
  1824. * Therefore all languages in the fallback array BEFORE this key will be skipped!
  1825. *
  1826. * @param {string=} langKey Contains the langKey the iteration shall start with. Set to false if you want to
  1827. * get back to the whole stack
  1828. */
  1829. $translate.useFallbackLanguage = function (langKey) {
  1830. if (langKey !== undefined && langKey !== null) {
  1831. if (!langKey) {
  1832. startFallbackIteration = 0;
  1833. } else {
  1834. var langKeyPosition = indexOf($fallbackLanguage, langKey);
  1835. if (langKeyPosition > -1) {
  1836. startFallbackIteration = langKeyPosition;
  1837. }
  1838. }
  1839. }
  1840. };
  1841. /**
  1842. * @ngdoc function
  1843. * @name pascalprecht.translate.$translate#proposedLanguage
  1844. * @methodOf pascalprecht.translate.$translate
  1845. *
  1846. * @description
  1847. * Returns the language key of language that is currently loaded asynchronously.
  1848. *
  1849. * @return {string} language key
  1850. */
  1851. $translate.proposedLanguage = function () {
  1852. return $nextLang;
  1853. };
  1854. /**
  1855. * @ngdoc function
  1856. * @name pascalprecht.translate.$translate#storage
  1857. * @methodOf pascalprecht.translate.$translate
  1858. *
  1859. * @description
  1860. * Returns registered storage.
  1861. *
  1862. * @return {object} Storage
  1863. */
  1864. $translate.storage = function () {
  1865. return Storage;
  1866. };
  1867. /**
  1868. * @ngdoc function
  1869. * @name pascalprecht.translate.$translate#negotiateLocale
  1870. * @methodOf pascalprecht.translate.$translate
  1871. *
  1872. * @description
  1873. * Returns a language key based on available languages and language aliases. If a
  1874. * language key cannot be resolved, returns undefined.
  1875. *
  1876. * If no or a falsy key is given, returns undefined.
  1877. *
  1878. * @param {string} [key] Language key
  1879. * @return {string|undefined} Language key or undefined if no language key is found.
  1880. */
  1881. $translate.negotiateLocale = negotiateLocale;
  1882. /**
  1883. * @ngdoc function
  1884. * @name pascalprecht.translate.$translate#use
  1885. * @methodOf pascalprecht.translate.$translate
  1886. *
  1887. * @description
  1888. * Tells angular-translate which language to use by given language key. This method is
  1889. * used to change language at runtime. It also takes care of storing the language
  1890. * key in a configured store to let your app remember the choosed language.
  1891. *
  1892. * When trying to 'use' a language which isn't available it tries to load it
  1893. * asynchronously with registered loaders.
  1894. *
  1895. * Returns promise object with loaded language file data or string of the currently used language.
  1896. *
  1897. * If no or a falsy key is given it returns the currently used language key.
  1898. * The returned string will be ```undefined``` if setting up $translate hasn't finished.
  1899. * @example
  1900. * $translate.use("en_US").then(function(data){
  1901. * $scope.text = $translate("HELLO");
  1902. * });
  1903. *
  1904. * @param {string} [key] Language key
  1905. * @return {object|string} Promise with loaded language data or the language key if a falsy param was given.
  1906. */
  1907. $translate.use = function (key) {
  1908. if (!key) {
  1909. return $uses;
  1910. }
  1911. var deferred = $q.defer();
  1912. $rootScope.$emit('$translateChangeStart', {language: key});
  1913. // Try to get the aliased language key
  1914. var aliasedKey = negotiateLocale(key);
  1915. if (aliasedKey) {
  1916. key = aliasedKey;
  1917. }
  1918. // if there isn't a translation table for the language we've requested,
  1919. // we load it asynchronously
  1920. if (($forceAsyncReloadEnabled || !$translationTable[key]) && $loaderFactory && !langPromises[key]) {
  1921. $nextLang = key;
  1922. langPromises[key] = loadAsync(key).then(function (translation) {
  1923. translations(translation.key, translation.table);
  1924. deferred.resolve(translation.key);
  1925. if ($nextLang === key) {
  1926. useLanguage(translation.key);
  1927. }
  1928. return translation;
  1929. }, function (key) {
  1930. $rootScope.$emit('$translateChangeError', {language: key});
  1931. deferred.reject(key);
  1932. $rootScope.$emit('$translateChangeEnd', {language: key});
  1933. return $q.reject(key);
  1934. });
  1935. langPromises[key]['finally'](function () {
  1936. clearNextLangAndPromise(key);
  1937. });
  1938. } else if ($nextLang === key && langPromises[key]) {
  1939. // we are already loading this asynchronously
  1940. // resolve our new deferred when the old langPromise is resolved
  1941. langPromises[key].then(function (translation) {
  1942. deferred.resolve(translation.key);
  1943. return translation;
  1944. }, function (key) {
  1945. deferred.reject(key);
  1946. return $q.reject(key);
  1947. });
  1948. } else {
  1949. deferred.resolve(key);
  1950. useLanguage(key);
  1951. }
  1952. return deferred.promise;
  1953. };
  1954. /**
  1955. * @ngdoc function
  1956. * @name pascalprecht.translate.$translate#storageKey
  1957. * @methodOf pascalprecht.translate.$translate
  1958. *
  1959. * @description
  1960. * Returns the key for the storage.
  1961. *
  1962. * @return {string} storage key
  1963. */
  1964. $translate.storageKey = function () {
  1965. return storageKey();
  1966. };
  1967. /**
  1968. * @ngdoc function
  1969. * @name pascalprecht.translate.$translate#isPostCompilingEnabled
  1970. * @methodOf pascalprecht.translate.$translate
  1971. *
  1972. * @description
  1973. * Returns whether post compiling is enabled or not
  1974. *
  1975. * @return {bool} storage key
  1976. */
  1977. $translate.isPostCompilingEnabled = function () {
  1978. return $postCompilingEnabled;
  1979. };
  1980. /**
  1981. * @ngdoc function
  1982. * @name pascalprecht.translate.$translate#isForceAsyncReloadEnabled
  1983. * @methodOf pascalprecht.translate.$translate
  1984. *
  1985. * @description
  1986. * Returns whether force async reload is enabled or not
  1987. *
  1988. * @return {boolean} forceAsyncReload value
  1989. */
  1990. $translate.isForceAsyncReloadEnabled = function () {
  1991. return $forceAsyncReloadEnabled;
  1992. };
  1993. /**
  1994. * @ngdoc function
  1995. * @name pascalprecht.translate.$translate#refresh
  1996. * @methodOf pascalprecht.translate.$translate
  1997. *
  1998. * @description
  1999. * Refreshes a translation table pointed by the given langKey. If langKey is not specified,
  2000. * the module will drop all existent translation tables and load new version of those which
  2001. * are currently in use.
  2002. *
  2003. * Refresh means that the module will drop target translation table and try to load it again.
  2004. *
  2005. * In case there are no loaders registered the refresh() method will throw an Error.
  2006. *
  2007. * If the module is able to refresh translation tables refresh() method will broadcast
  2008. * $translateRefreshStart and $translateRefreshEnd events.
  2009. *
  2010. * @example
  2011. * // this will drop all currently existent translation tables and reload those which are
  2012. * // currently in use
  2013. * $translate.refresh();
  2014. * // this will refresh a translation table for the en_US language
  2015. * $translate.refresh('en_US');
  2016. *
  2017. * @param {string} langKey A language key of the table, which has to be refreshed
  2018. *
  2019. * @return {promise} Promise, which will be resolved in case a translation tables refreshing
  2020. * process is finished successfully, and reject if not.
  2021. */
  2022. $translate.refresh = function (langKey) {
  2023. if (!$loaderFactory) {
  2024. throw new Error('Couldn\'t refresh translation table, no loader registered!');
  2025. }
  2026. var deferred = $q.defer();
  2027. function resolve() {
  2028. deferred.resolve();
  2029. $rootScope.$emit('$translateRefreshEnd', {language: langKey});
  2030. }
  2031. function reject() {
  2032. deferred.reject();
  2033. $rootScope.$emit('$translateRefreshEnd', {language: langKey});
  2034. }
  2035. $rootScope.$emit('$translateRefreshStart', {language: langKey});
  2036. if (!langKey) {
  2037. // if there's no language key specified we refresh ALL THE THINGS!
  2038. var tables = [], loadingKeys = {};
  2039. // reload registered fallback languages
  2040. if ($fallbackLanguage && $fallbackLanguage.length) {
  2041. for (var i = 0, len = $fallbackLanguage.length; i < len; i++) {
  2042. tables.push(loadAsync($fallbackLanguage[i]));
  2043. loadingKeys[$fallbackLanguage[i]] = true;
  2044. }
  2045. }
  2046. // reload currently used language
  2047. if ($uses && !loadingKeys[$uses]) {
  2048. tables.push(loadAsync($uses));
  2049. }
  2050. var allTranslationsLoaded = function (tableData) {
  2051. $translationTable = {};
  2052. angular.forEach(tableData, function (data) {
  2053. translations(data.key, data.table);
  2054. });
  2055. if ($uses) {
  2056. useLanguage($uses);
  2057. }
  2058. resolve();
  2059. };
  2060. allTranslationsLoaded.displayName = 'refreshPostProcessor';
  2061. $q.all(tables).then(allTranslationsLoaded, reject);
  2062. } else if ($translationTable[langKey]) {
  2063. var oneTranslationsLoaded = function (data) {
  2064. translations(data.key, data.table);
  2065. if (langKey === $uses) {
  2066. useLanguage($uses);
  2067. }
  2068. resolve();
  2069. };
  2070. oneTranslationsLoaded.displayName = 'refreshPostProcessor';
  2071. loadAsync(langKey).then(oneTranslationsLoaded, reject);
  2072. } else {
  2073. reject();
  2074. }
  2075. return deferred.promise;
  2076. };
  2077. /**
  2078. * @ngdoc function
  2079. * @name pascalprecht.translate.$translate#instant
  2080. * @methodOf pascalprecht.translate.$translate
  2081. *
  2082. * @description
  2083. * Returns a translation instantly from the internal state of loaded translation. All rules
  2084. * regarding the current language, the preferred language of even fallback languages will be
  2085. * used except any promise handling. If a language was not found, an asynchronous loading
  2086. * will be invoked in the background.
  2087. *
  2088. * @param {string|array} translationId A token which represents a translation id
  2089. * This can be optionally an array of translation ids which
  2090. * results that the function's promise returns an object where
  2091. * each key is the translation id and the value the translation.
  2092. * @param {object} interpolateParams Params
  2093. * @param {string} interpolationId The id of the interpolation to use
  2094. * @param {string} forceLanguage A language to be used instead of the current language
  2095. *
  2096. * @return {string|object} translation
  2097. */
  2098. $translate.instant = function (translationId, interpolateParams, interpolationId, forceLanguage) {
  2099. // we don't want to re-negotiate $uses
  2100. var uses = (forceLanguage && forceLanguage !== $uses) ? // we don't want to re-negotiate $uses
  2101. (negotiateLocale(forceLanguage) || forceLanguage) : $uses;
  2102. // Detect undefined and null values to shorten the execution and prevent exceptions
  2103. if (translationId === null || angular.isUndefined(translationId)) {
  2104. return translationId;
  2105. }
  2106. // Duck detection: If the first argument is an array, a bunch of translations was requested.
  2107. // The result is an object.
  2108. if (angular.isArray(translationId)) {
  2109. var results = {};
  2110. for (var i = 0, c = translationId.length; i < c; i++) {
  2111. results[translationId[i]] = $translate.instant(translationId[i], interpolateParams, interpolationId, forceLanguage);
  2112. }
  2113. return results;
  2114. }
  2115. // We discarded unacceptable values. So we just need to verify if translationId is empty String
  2116. if (angular.isString(translationId) && translationId.length < 1) {
  2117. return translationId;
  2118. }
  2119. // trim off any whitespace
  2120. if (translationId) {
  2121. translationId = trim.apply(translationId);
  2122. }
  2123. var result, possibleLangKeys = [];
  2124. if ($preferredLanguage) {
  2125. possibleLangKeys.push($preferredLanguage);
  2126. }
  2127. if (uses) {
  2128. possibleLangKeys.push(uses);
  2129. }
  2130. if ($fallbackLanguage && $fallbackLanguage.length) {
  2131. possibleLangKeys = possibleLangKeys.concat($fallbackLanguage);
  2132. }
  2133. for (var j = 0, d = possibleLangKeys.length; j < d; j++) {
  2134. var possibleLangKey = possibleLangKeys[j];
  2135. if ($translationTable[possibleLangKey]) {
  2136. if (typeof $translationTable[possibleLangKey][translationId] !== 'undefined') {
  2137. result = determineTranslationInstant(translationId, interpolateParams, interpolationId, uses);
  2138. }
  2139. }
  2140. if (typeof result !== 'undefined') {
  2141. break;
  2142. }
  2143. }
  2144. if (!result && result !== '') {
  2145. if ($notFoundIndicatorLeft || $notFoundIndicatorRight) {
  2146. result = applyNotFoundIndicators(translationId);
  2147. } else {
  2148. // Return translation of default interpolator if not found anything.
  2149. result = defaultInterpolator.interpolate(translationId, interpolateParams);
  2150. if ($missingTranslationHandlerFactory && !pendingLoader) {
  2151. result = translateByHandler(translationId, interpolateParams);
  2152. }
  2153. }
  2154. }
  2155. return result;
  2156. };
  2157. /**
  2158. * @ngdoc function
  2159. * @name pascalprecht.translate.$translate#versionInfo
  2160. * @methodOf pascalprecht.translate.$translate
  2161. *
  2162. * @description
  2163. * Returns the current version information for the angular-translate library
  2164. *
  2165. * @return {string} angular-translate version
  2166. */
  2167. $translate.versionInfo = function () {
  2168. return version;
  2169. };
  2170. /**
  2171. * @ngdoc function
  2172. * @name pascalprecht.translate.$translate#loaderCache
  2173. * @methodOf pascalprecht.translate.$translate
  2174. *
  2175. * @description
  2176. * Returns the defined loaderCache.
  2177. *
  2178. * @return {boolean|string|object} current value of loaderCache
  2179. */
  2180. $translate.loaderCache = function () {
  2181. return loaderCache;
  2182. };
  2183. // internal purpose only
  2184. $translate.directivePriority = function () {
  2185. return directivePriority;
  2186. };
  2187. // internal purpose only
  2188. $translate.statefulFilter = function () {
  2189. return statefulFilter;
  2190. };
  2191. /**
  2192. * @ngdoc function
  2193. * @name pascalprecht.translate.$translate#isReady
  2194. * @methodOf pascalprecht.translate.$translate
  2195. *
  2196. * @description
  2197. * Returns whether the service is "ready" to translate (i.e. loading 1st language).
  2198. *
  2199. * See also {@link pascalprecht.translate.$translate#methods_onReady onReady()}.
  2200. *
  2201. * @return {boolean} current value of ready
  2202. */
  2203. $translate.isReady = function () {
  2204. return $isReady;
  2205. };
  2206. var $onReadyDeferred = $q.defer();
  2207. $onReadyDeferred.promise.then(function () {
  2208. $isReady = true;
  2209. });
  2210. /**
  2211. * @ngdoc function
  2212. * @name pascalprecht.translate.$translate#onReady
  2213. * @methodOf pascalprecht.translate.$translate
  2214. *
  2215. * @description
  2216. * Returns whether the service is "ready" to translate (i.e. loading 1st language).
  2217. *
  2218. * See also {@link pascalprecht.translate.$translate#methods_isReady isReady()}.
  2219. *
  2220. * @param {Function=} fn Function to invoke when service is ready
  2221. * @return {object} Promise resolved when service is ready
  2222. */
  2223. $translate.onReady = function (fn) {
  2224. var deferred = $q.defer();
  2225. if (angular.isFunction(fn)) {
  2226. deferred.promise.then(fn);
  2227. }
  2228. if ($isReady) {
  2229. deferred.resolve();
  2230. } else {
  2231. $onReadyDeferred.promise.then(deferred.resolve);
  2232. }
  2233. return deferred.promise;
  2234. };
  2235. // Whenever $translateReady is being fired, this will ensure the state of $isReady
  2236. var globalOnReadyListener = $rootScope.$on('$translateReady', function () {
  2237. $onReadyDeferred.resolve();
  2238. globalOnReadyListener(); // one time only
  2239. globalOnReadyListener = null;
  2240. });
  2241. var globalOnChangeListener = $rootScope.$on('$translateChangeEnd', function () {
  2242. $onReadyDeferred.resolve();
  2243. globalOnChangeListener(); // one time only
  2244. globalOnChangeListener = null;
  2245. });
  2246. if ($loaderFactory) {
  2247. // If at least one async loader is defined and there are no
  2248. // (default) translations available we should try to load them.
  2249. if (angular.equals($translationTable, {})) {
  2250. if ($translate.use()) {
  2251. $translate.use($translate.use());
  2252. }
  2253. }
  2254. // Also, if there are any fallback language registered, we start
  2255. // loading them asynchronously as soon as we can.
  2256. if ($fallbackLanguage && $fallbackLanguage.length) {
  2257. var processAsyncResult = function (translation) {
  2258. translations(translation.key, translation.table);
  2259. $rootScope.$emit('$translateChangeEnd', { language: translation.key });
  2260. return translation;
  2261. };
  2262. for (var i = 0, len = $fallbackLanguage.length; i < len; i++) {
  2263. var fallbackLanguageId = $fallbackLanguage[i];
  2264. if ($forceAsyncReloadEnabled || !$translationTable[fallbackLanguageId]) {
  2265. langPromises[fallbackLanguageId] = loadAsync(fallbackLanguageId).then(processAsyncResult);
  2266. }
  2267. }
  2268. }
  2269. } else {
  2270. $rootScope.$emit('$translateReady', { language: $translate.use() });
  2271. }
  2272. return $translate;
  2273. }
  2274. ];
  2275. }
  2276. $translate.$inject = ['$STORAGE_KEY', '$windowProvider', '$translateSanitizationProvider', 'pascalprechtTranslateOverrider'];
  2277. $translate.displayName = 'displayName';
  2278. /**
  2279. * @ngdoc object
  2280. * @name pascalprecht.translate.$translateDefaultInterpolation
  2281. * @requires $interpolate
  2282. *
  2283. * @description
  2284. * Uses angular's `$interpolate` services to interpolate strings against some values.
  2285. *
  2286. * Be aware to configure a proper sanitization strategy.
  2287. *
  2288. * See also:
  2289. * * {@link pascalprecht.translate.$translateSanitization}
  2290. *
  2291. * @return {object} $translateDefaultInterpolation Interpolator service
  2292. */
  2293. angular.module('pascalprecht.translate').factory('$translateDefaultInterpolation', $translateDefaultInterpolation);
  2294. function $translateDefaultInterpolation ($interpolate, $translateSanitization) {
  2295. 'use strict';
  2296. var $translateInterpolator = {},
  2297. $locale,
  2298. $identifier = 'default';
  2299. /**
  2300. * @ngdoc function
  2301. * @name pascalprecht.translate.$translateDefaultInterpolation#setLocale
  2302. * @methodOf pascalprecht.translate.$translateDefaultInterpolation
  2303. *
  2304. * @description
  2305. * Sets current locale (this is currently not use in this interpolation).
  2306. *
  2307. * @param {string} locale Language key or locale.
  2308. */
  2309. $translateInterpolator.setLocale = function (locale) {
  2310. $locale = locale;
  2311. };
  2312. /**
  2313. * @ngdoc function
  2314. * @name pascalprecht.translate.$translateDefaultInterpolation#getInterpolationIdentifier
  2315. * @methodOf pascalprecht.translate.$translateDefaultInterpolation
  2316. *
  2317. * @description
  2318. * Returns an identifier for this interpolation service.
  2319. *
  2320. * @returns {string} $identifier
  2321. */
  2322. $translateInterpolator.getInterpolationIdentifier = function () {
  2323. return $identifier;
  2324. };
  2325. /**
  2326. * @deprecated will be removed in 3.0
  2327. * @see {@link pascalprecht.translate.$translateSanitization}
  2328. */
  2329. $translateInterpolator.useSanitizeValueStrategy = function (value) {
  2330. $translateSanitization.useStrategy(value);
  2331. return this;
  2332. };
  2333. /**
  2334. * @ngdoc function
  2335. * @name pascalprecht.translate.$translateDefaultInterpolation#interpolate
  2336. * @methodOf pascalprecht.translate.$translateDefaultInterpolation
  2337. *
  2338. * @description
  2339. * Interpolates given string agains given interpolate params using angulars
  2340. * `$interpolate` service.
  2341. *
  2342. * @returns {string} interpolated string.
  2343. */
  2344. $translateInterpolator.interpolate = function (string, interpolationParams) {
  2345. interpolationParams = interpolationParams || {};
  2346. interpolationParams = $translateSanitization.sanitize(interpolationParams, 'params');
  2347. var interpolatedText = $interpolate(string)(interpolationParams);
  2348. interpolatedText = $translateSanitization.sanitize(interpolatedText, 'text');
  2349. return interpolatedText;
  2350. };
  2351. return $translateInterpolator;
  2352. }
  2353. $translateDefaultInterpolation.$inject = ['$interpolate', '$translateSanitization'];
  2354. $translateDefaultInterpolation.displayName = '$translateDefaultInterpolation';
  2355. angular.module('pascalprecht.translate').constant('$STORAGE_KEY', 'NG_TRANSLATE_LANG_KEY');
  2356. angular.module('pascalprecht.translate')
  2357. /**
  2358. * @ngdoc directive
  2359. * @name pascalprecht.translate.directive:translate
  2360. * @requires $compile
  2361. * @requires $filter
  2362. * @requires $interpolate
  2363. * @restrict AE
  2364. *
  2365. * @description
  2366. * Translates given translation id either through attribute or DOM content.
  2367. * Internally it uses `translate` filter to translate translation id. It possible to
  2368. * pass an optional `translate-values` object literal as string into translation id.
  2369. *
  2370. * @param {string=} translate Translation id which could be either string or interpolated string.
  2371. * @param {string=} translate-values Values to pass into translation id. Can be passed as object literal string or interpolated object.
  2372. * @param {string=} translate-attr-ATTR translate Translation id and put it into ATTR attribute.
  2373. * @param {string=} translate-default will be used unless translation was successful
  2374. * @param {boolean=} translate-compile (default true if present) defines locally activation of {@link pascalprecht.translate.$translateProvider#methods_usePostCompiling}
  2375. *
  2376. * @example
  2377. <example module="ngView">
  2378. <file name="index.html">
  2379. <div ng-controller="TranslateCtrl">
  2380. <pre translate="TRANSLATION_ID"></pre>
  2381. <pre translate>TRANSLATION_ID</pre>
  2382. <pre translate translate-attr-title="TRANSLATION_ID"></pre>
  2383. <pre translate="{{translationId}}"></pre>
  2384. <pre translate>{{translationId}}</pre>
  2385. <pre translate="WITH_VALUES" translate-values="{value: 5}"></pre>
  2386. <pre translate translate-values="{value: 5}">WITH_VALUES</pre>
  2387. <pre translate="WITH_VALUES" translate-values="{{values}}"></pre>
  2388. <pre translate translate-values="{{values}}">WITH_VALUES</pre>
  2389. <pre translate translate-attr-title="WITH_VALUES" translate-values="{{values}}"></pre>
  2390. </div>
  2391. </file>
  2392. <file name="script.js">
  2393. angular.module('ngView', ['pascalprecht.translate'])
  2394. .config(function ($translateProvider) {
  2395. $translateProvider.translations('en',{
  2396. 'TRANSLATION_ID': 'Hello there!',
  2397. 'WITH_VALUES': 'The following value is dynamic: {{value}}'
  2398. }).preferredLanguage('en');
  2399. });
  2400. angular.module('ngView').controller('TranslateCtrl', function ($scope) {
  2401. $scope.translationId = 'TRANSLATION_ID';
  2402. $scope.values = {
  2403. value: 78
  2404. };
  2405. });
  2406. </file>
  2407. <file name="scenario.js">
  2408. it('should translate', function () {
  2409. inject(function ($rootScope, $compile) {
  2410. $rootScope.translationId = 'TRANSLATION_ID';
  2411. element = $compile('<p translate="TRANSLATION_ID"></p>')($rootScope);
  2412. $rootScope.$digest();
  2413. expect(element.text()).toBe('Hello there!');
  2414. element = $compile('<p translate="{{translationId}}"></p>')($rootScope);
  2415. $rootScope.$digest();
  2416. expect(element.text()).toBe('Hello there!');
  2417. element = $compile('<p translate>TRANSLATION_ID</p>')($rootScope);
  2418. $rootScope.$digest();
  2419. expect(element.text()).toBe('Hello there!');
  2420. element = $compile('<p translate>{{translationId}}</p>')($rootScope);
  2421. $rootScope.$digest();
  2422. expect(element.text()).toBe('Hello there!');
  2423. element = $compile('<p translate translate-attr-title="TRANSLATION_ID"></p>')($rootScope);
  2424. $rootScope.$digest();
  2425. expect(element.attr('title')).toBe('Hello there!');
  2426. });
  2427. });
  2428. </file>
  2429. </example>
  2430. */
  2431. .directive('translate', translateDirective);
  2432. function translateDirective($translate, $q, $interpolate, $compile, $parse, $rootScope) {
  2433. 'use strict';
  2434. /**
  2435. * @name trim
  2436. * @private
  2437. *
  2438. * @description
  2439. * trim polyfill
  2440. *
  2441. * @returns {string} The string stripped of whitespace from both ends
  2442. */
  2443. var trim = function() {
  2444. return this.toString().replace(/^\s+|\s+$/g, '');
  2445. };
  2446. return {
  2447. restrict: 'AE',
  2448. scope: true,
  2449. priority: $translate.directivePriority(),
  2450. compile: function (tElement, tAttr) {
  2451. var translateValuesExist = (tAttr.translateValues) ?
  2452. tAttr.translateValues : undefined;
  2453. var translateInterpolation = (tAttr.translateInterpolation) ?
  2454. tAttr.translateInterpolation : undefined;
  2455. var translateValueExist = tElement[0].outerHTML.match(/translate-value-+/i);
  2456. var interpolateRegExp = '^(.*)(' + $interpolate.startSymbol() + '.*' + $interpolate.endSymbol() + ')(.*)',
  2457. watcherRegExp = '^(.*)' + $interpolate.startSymbol() + '(.*)' + $interpolate.endSymbol() + '(.*)';
  2458. return function linkFn(scope, iElement, iAttr) {
  2459. scope.interpolateParams = {};
  2460. scope.preText = '';
  2461. scope.postText = '';
  2462. scope.translateNamespace = getTranslateNamespace(scope);
  2463. var translationIds = {};
  2464. var initInterpolationParams = function (interpolateParams, iAttr, tAttr) {
  2465. // initial setup
  2466. if (iAttr.translateValues) {
  2467. angular.extend(interpolateParams, $parse(iAttr.translateValues)(scope.$parent));
  2468. }
  2469. // initially fetch all attributes if existing and fill the params
  2470. if (translateValueExist) {
  2471. for (var attr in tAttr) {
  2472. if (Object.prototype.hasOwnProperty.call(iAttr, attr) && attr.substr(0, 14) === 'translateValue' && attr !== 'translateValues') {
  2473. var attributeName = angular.lowercase(attr.substr(14, 1)) + attr.substr(15);
  2474. interpolateParams[attributeName] = tAttr[attr];
  2475. }
  2476. }
  2477. }
  2478. };
  2479. // Ensures any change of the attribute "translate" containing the id will
  2480. // be re-stored to the scope's "translationId".
  2481. // If the attribute has no content, the element's text value (white spaces trimmed off) will be used.
  2482. var observeElementTranslation = function (translationId) {
  2483. // Remove any old watcher
  2484. if (angular.isFunction(observeElementTranslation._unwatchOld)) {
  2485. observeElementTranslation._unwatchOld();
  2486. observeElementTranslation._unwatchOld = undefined;
  2487. }
  2488. if (angular.equals(translationId , '') || !angular.isDefined(translationId)) {
  2489. var iElementText = trim.apply(iElement.text());
  2490. // Resolve translation id by inner html if required
  2491. var interpolateMatches = iElementText.match(interpolateRegExp);
  2492. // Interpolate translation id if required
  2493. if (angular.isArray(interpolateMatches)) {
  2494. scope.preText = interpolateMatches[1];
  2495. scope.postText = interpolateMatches[3];
  2496. translationIds.translate = $interpolate(interpolateMatches[2])(scope.$parent);
  2497. var watcherMatches = iElementText.match(watcherRegExp);
  2498. if (angular.isArray(watcherMatches) && watcherMatches[2] && watcherMatches[2].length) {
  2499. observeElementTranslation._unwatchOld = scope.$watch(watcherMatches[2], function (newValue) {
  2500. translationIds.translate = newValue;
  2501. updateTranslations();
  2502. });
  2503. }
  2504. } else {
  2505. // do not assigne the translation id if it is empty.
  2506. translationIds.translate = !iElementText ? undefined : iElementText;
  2507. }
  2508. } else {
  2509. translationIds.translate = translationId;
  2510. }
  2511. updateTranslations();
  2512. };
  2513. var observeAttributeTranslation = function (translateAttr) {
  2514. iAttr.$observe(translateAttr, function (translationId) {
  2515. translationIds[translateAttr] = translationId;
  2516. updateTranslations();
  2517. });
  2518. };
  2519. // initial setup with values
  2520. initInterpolationParams(scope.interpolateParams, iAttr, tAttr);
  2521. var firstAttributeChangedEvent = true;
  2522. iAttr.$observe('translate', function (translationId) {
  2523. if (typeof translationId === 'undefined') {
  2524. // case of element "<translate>xyz</translate>"
  2525. observeElementTranslation('');
  2526. } else {
  2527. // case of regular attribute
  2528. if (translationId !== '' || !firstAttributeChangedEvent) {
  2529. translationIds.translate = translationId;
  2530. updateTranslations();
  2531. }
  2532. }
  2533. firstAttributeChangedEvent = false;
  2534. });
  2535. for (var translateAttr in iAttr) {
  2536. if (iAttr.hasOwnProperty(translateAttr) && translateAttr.substr(0, 13) === 'translateAttr') {
  2537. observeAttributeTranslation(translateAttr);
  2538. }
  2539. }
  2540. iAttr.$observe('translateDefault', function (value) {
  2541. scope.defaultText = value;
  2542. updateTranslations();
  2543. });
  2544. if (translateValuesExist) {
  2545. iAttr.$observe('translateValues', function (interpolateParams) {
  2546. if (interpolateParams) {
  2547. scope.$parent.$watch(function () {
  2548. angular.extend(scope.interpolateParams, $parse(interpolateParams)(scope.$parent));
  2549. });
  2550. }
  2551. });
  2552. }
  2553. if (translateValueExist) {
  2554. var observeValueAttribute = function (attrName) {
  2555. iAttr.$observe(attrName, function (value) {
  2556. var attributeName = angular.lowercase(attrName.substr(14, 1)) + attrName.substr(15);
  2557. scope.interpolateParams[attributeName] = value;
  2558. });
  2559. };
  2560. for (var attr in iAttr) {
  2561. if (Object.prototype.hasOwnProperty.call(iAttr, attr) && attr.substr(0, 14) === 'translateValue' && attr !== 'translateValues') {
  2562. observeValueAttribute(attr);
  2563. }
  2564. }
  2565. }
  2566. // Master update function
  2567. var updateTranslations = function () {
  2568. for (var key in translationIds) {
  2569. if (translationIds.hasOwnProperty(key) && translationIds[key] !== undefined) {
  2570. updateTranslation(key, translationIds[key], scope, scope.interpolateParams, scope.defaultText, scope.translateNamespace);
  2571. }
  2572. }
  2573. };
  2574. // Put translation processing function outside loop
  2575. var updateTranslation = function(translateAttr, translationId, scope, interpolateParams, defaultTranslationText, translateNamespace) {
  2576. if (translationId) {
  2577. // if translation id starts with '.' and translateNamespace given, prepend namespace
  2578. if (translateNamespace && translationId.charAt(0) === '.') {
  2579. translationId = translateNamespace + translationId;
  2580. }
  2581. $translate(translationId, interpolateParams, translateInterpolation, defaultTranslationText, scope.translateLanguage)
  2582. .then(function (translation) {
  2583. applyTranslation(translation, scope, true, translateAttr);
  2584. }, function (translationId) {
  2585. applyTranslation(translationId, scope, false, translateAttr);
  2586. });
  2587. } else {
  2588. // as an empty string cannot be translated, we can solve this using successful=false
  2589. applyTranslation(translationId, scope, false, translateAttr);
  2590. }
  2591. };
  2592. var applyTranslation = function (value, scope, successful, translateAttr) {
  2593. if (translateAttr === 'translate') {
  2594. // default translate into innerHTML
  2595. if (!successful && typeof scope.defaultText !== 'undefined') {
  2596. value = scope.defaultText;
  2597. }
  2598. iElement.empty().append(scope.preText + value + scope.postText);
  2599. var globallyEnabled = $translate.isPostCompilingEnabled();
  2600. var locallyDefined = typeof tAttr.translateCompile !== 'undefined';
  2601. var locallyEnabled = locallyDefined && tAttr.translateCompile !== 'false';
  2602. if ((globallyEnabled && !locallyDefined) || locallyEnabled) {
  2603. $compile(iElement.contents())(scope);
  2604. }
  2605. } else {
  2606. // translate attribute
  2607. if (!successful && typeof scope.defaultText !== 'undefined') {
  2608. value = scope.defaultText;
  2609. }
  2610. var attributeName = iAttr.$attr[translateAttr];
  2611. if (attributeName.substr(0, 5) === 'data-') {
  2612. // ensure html5 data prefix is stripped
  2613. attributeName = attributeName.substr(5);
  2614. }
  2615. attributeName = attributeName.substr(15);
  2616. iElement.attr(attributeName, value);
  2617. }
  2618. };
  2619. if (translateValuesExist || translateValueExist || iAttr.translateDefault) {
  2620. scope.$watch('interpolateParams', updateTranslations, true);
  2621. }
  2622. scope.$watch('translateLanguage', updateTranslations);
  2623. // Ensures the text will be refreshed after the current language was changed
  2624. // w/ $translate.use(...)
  2625. var unbind = $rootScope.$on('$translateChangeSuccess', updateTranslations);
  2626. // ensure translation will be looked up at least one
  2627. if (iElement.text().length) {
  2628. if (iAttr.translate) {
  2629. observeElementTranslation(iAttr.translate);
  2630. } else {
  2631. observeElementTranslation('');
  2632. }
  2633. } else if (iAttr.translate) {
  2634. // ensure attribute will be not skipped
  2635. observeElementTranslation(iAttr.translate);
  2636. }
  2637. updateTranslations();
  2638. scope.$on('$destroy', unbind);
  2639. };
  2640. }
  2641. };
  2642. }
  2643. translateDirective.$inject = ['$translate', '$q', '$interpolate', '$compile', '$parse', '$rootScope'];
  2644. /**
  2645. * Returns the scope's namespace.
  2646. * @private
  2647. * @param scope
  2648. * @returns {string}
  2649. */
  2650. function getTranslateNamespace(scope) {
  2651. 'use strict';
  2652. if (scope.translateNamespace) {
  2653. return scope.translateNamespace;
  2654. }
  2655. if (scope.$parent) {
  2656. return getTranslateNamespace(scope.$parent);
  2657. }
  2658. }
  2659. translateDirective.displayName = 'translateDirective';
  2660. angular.module('pascalprecht.translate')
  2661. /**
  2662. * @ngdoc directive
  2663. * @name pascalprecht.translate.directive:translateCloak
  2664. * @requires $rootScope
  2665. * @requires $translate
  2666. * @restrict A
  2667. *
  2668. * $description
  2669. * Adds a `translate-cloak` class name to the given element where this directive
  2670. * is applied initially and removes it, once a loader has finished loading.
  2671. *
  2672. * This directive can be used to prevent initial flickering when loading translation
  2673. * data asynchronously.
  2674. *
  2675. * The class name is defined in
  2676. * {@link pascalprecht.translate.$translateProvider#cloakClassName $translate.cloakClassName()}.
  2677. *
  2678. * @param {string=} translate-cloak If a translationId is provided, it will be used for showing
  2679. * or hiding the cloak. Basically it relies on the translation
  2680. * resolve.
  2681. */
  2682. .directive('translateCloak', translateCloakDirective);
  2683. function translateCloakDirective($translate, $rootScope) {
  2684. 'use strict';
  2685. return {
  2686. compile: function (tElement) {
  2687. var applyCloak = function () {
  2688. tElement.addClass($translate.cloakClassName());
  2689. },
  2690. removeCloak = function () {
  2691. tElement.removeClass($translate.cloakClassName());
  2692. };
  2693. $translate.onReady(function () {
  2694. removeCloak();
  2695. });
  2696. applyCloak();
  2697. return function linkFn(scope, iElement, iAttr) {
  2698. if (iAttr.translateCloak && iAttr.translateCloak.length) {
  2699. // Register a watcher for the defined translation allowing a fine tuned cloak
  2700. iAttr.$observe('translateCloak', function (translationId) {
  2701. $translate(translationId).then(removeCloak, applyCloak);
  2702. });
  2703. // Register for change events as this is being another indicicator revalidating the cloak)
  2704. $rootScope.$on('$translateChangeSuccess', function () {
  2705. $translate(iAttr.translateCloak).then(removeCloak, applyCloak);
  2706. });
  2707. }
  2708. };
  2709. }
  2710. };
  2711. }
  2712. translateCloakDirective.$inject = ['$translate', '$rootScope'];
  2713. translateCloakDirective.displayName = 'translateCloakDirective';
  2714. angular.module('pascalprecht.translate')
  2715. /**
  2716. * @ngdoc directive
  2717. * @name pascalprecht.translate.directive:translateNamespace
  2718. * @restrict A
  2719. *
  2720. * @description
  2721. * Translates given translation id either through attribute or DOM content.
  2722. * Internally it uses `translate` filter to translate translation id. It possible to
  2723. * pass an optional `translate-values` object literal as string into translation id.
  2724. *
  2725. * @param {string=} translate namespace name which could be either string or interpolated string.
  2726. *
  2727. * @example
  2728. <example module="ngView">
  2729. <file name="index.html">
  2730. <div translate-namespace="CONTENT">
  2731. <div>
  2732. <h1 translate>.HEADERS.TITLE</h1>
  2733. <h1 translate>.HEADERS.WELCOME</h1>
  2734. </div>
  2735. <div translate-namespace=".HEADERS">
  2736. <h1 translate>.TITLE</h1>
  2737. <h1 translate>.WELCOME</h1>
  2738. </div>
  2739. </div>
  2740. </file>
  2741. <file name="script.js">
  2742. angular.module('ngView', ['pascalprecht.translate'])
  2743. .config(function ($translateProvider) {
  2744. $translateProvider.translations('en',{
  2745. 'TRANSLATION_ID': 'Hello there!',
  2746. 'CONTENT': {
  2747. 'HEADERS': {
  2748. TITLE: 'Title'
  2749. }
  2750. },
  2751. 'CONTENT.HEADERS.WELCOME': 'Welcome'
  2752. }).preferredLanguage('en');
  2753. });
  2754. </file>
  2755. </example>
  2756. */
  2757. .directive('translateNamespace', translateNamespaceDirective);
  2758. function translateNamespaceDirective() {
  2759. 'use strict';
  2760. return {
  2761. restrict: 'A',
  2762. scope: true,
  2763. compile: function () {
  2764. return {
  2765. pre: function (scope, iElement, iAttrs) {
  2766. scope.translateNamespace = getTranslateNamespace(scope);
  2767. if (scope.translateNamespace && iAttrs.translateNamespace.charAt(0) === '.') {
  2768. scope.translateNamespace += iAttrs.translateNamespace;
  2769. } else {
  2770. scope.translateNamespace = iAttrs.translateNamespace;
  2771. }
  2772. }
  2773. };
  2774. }
  2775. };
  2776. }
  2777. /**
  2778. * Returns the scope's namespace.
  2779. * @private
  2780. * @param scope
  2781. * @returns {string}
  2782. */
  2783. function getTranslateNamespace(scope) {
  2784. 'use strict';
  2785. if (scope.translateNamespace) {
  2786. return scope.translateNamespace;
  2787. }
  2788. if (scope.$parent) {
  2789. return getTranslateNamespace(scope.$parent);
  2790. }
  2791. }
  2792. translateNamespaceDirective.displayName = 'translateNamespaceDirective';
  2793. angular.module('pascalprecht.translate')
  2794. /**
  2795. * @ngdoc directive
  2796. * @name pascalprecht.translate.directive:translateLanguage
  2797. * @restrict A
  2798. *
  2799. * @description
  2800. * Forces the language to the directives in the underlying scope.
  2801. *
  2802. * @param {string=} translate language that will be negotiated.
  2803. *
  2804. * @example
  2805. <example module="ngView">
  2806. <file name="index.html">
  2807. <div>
  2808. <div>
  2809. <h1 translate>HELLO</h1>
  2810. </div>
  2811. <div translate-language="de">
  2812. <h1 translate>HELLO</h1>
  2813. </div>
  2814. </div>
  2815. </file>
  2816. <file name="script.js">
  2817. angular.module('ngView', ['pascalprecht.translate'])
  2818. .config(function ($translateProvider) {
  2819. $translateProvider
  2820. .translations('en',{
  2821. 'HELLO': 'Hello world!'
  2822. })
  2823. .translations('de',{
  2824. 'HELLO': 'Hallo Welt!'
  2825. })
  2826. .translations(.preferredLanguage('en');
  2827. });
  2828. </file>
  2829. </example>
  2830. */
  2831. .directive('translateLanguage', translateLanguageDirective);
  2832. function translateLanguageDirective() {
  2833. 'use strict';
  2834. return {
  2835. restrict: 'A',
  2836. scope: true,
  2837. compile: function () {
  2838. return function linkFn(scope, iElement, iAttrs) {
  2839. iAttrs.$observe('translateLanguage', function (newTranslateLanguage) {
  2840. scope.translateLanguage = newTranslateLanguage;
  2841. });
  2842. };
  2843. }
  2844. };
  2845. }
  2846. translateLanguageDirective.displayName = 'translateLanguageDirective';
  2847. angular.module('pascalprecht.translate')
  2848. /**
  2849. * @ngdoc filter
  2850. * @name pascalprecht.translate.filter:translate
  2851. * @requires $parse
  2852. * @requires pascalprecht.translate.$translate
  2853. * @function
  2854. *
  2855. * @description
  2856. * Uses `$translate` service to translate contents. Accepts interpolate parameters
  2857. * to pass dynamized values though translation.
  2858. *
  2859. * @param {string} translationId A translation id to be translated.
  2860. * @param {*=} interpolateParams Optional object literal (as hash or string) to pass values into translation.
  2861. *
  2862. * @returns {string} Translated text.
  2863. *
  2864. * @example
  2865. <example module="ngView">
  2866. <file name="index.html">
  2867. <div ng-controller="TranslateCtrl">
  2868. <pre>{{ 'TRANSLATION_ID' | translate }}</pre>
  2869. <pre>{{ translationId | translate }}</pre>
  2870. <pre>{{ 'WITH_VALUES' | translate:'{value: 5}' }}</pre>
  2871. <pre>{{ 'WITH_VALUES' | translate:values }}</pre>
  2872. </div>
  2873. </file>
  2874. <file name="script.js">
  2875. angular.module('ngView', ['pascalprecht.translate'])
  2876. .config(function ($translateProvider) {
  2877. $translateProvider.translations('en', {
  2878. 'TRANSLATION_ID': 'Hello there!',
  2879. 'WITH_VALUES': 'The following value is dynamic: {{value}}'
  2880. });
  2881. $translateProvider.preferredLanguage('en');
  2882. });
  2883. angular.module('ngView').controller('TranslateCtrl', function ($scope) {
  2884. $scope.translationId = 'TRANSLATION_ID';
  2885. $scope.values = {
  2886. value: 78
  2887. };
  2888. });
  2889. </file>
  2890. </example>
  2891. */
  2892. .filter('translate', translateFilterFactory);
  2893. function translateFilterFactory($parse, $translate) {
  2894. 'use strict';
  2895. var translateFilter = function (translationId, interpolateParams, interpolation, forceLanguage) {
  2896. if (!angular.isObject(interpolateParams)) {
  2897. interpolateParams = $parse(interpolateParams)(this);
  2898. }
  2899. return $translate.instant(translationId, interpolateParams, interpolation, forceLanguage);
  2900. };
  2901. if ($translate.statefulFilter()) {
  2902. translateFilter.$stateful = true;
  2903. }
  2904. return translateFilter;
  2905. }
  2906. translateFilterFactory.$inject = ['$parse', '$translate'];
  2907. translateFilterFactory.displayName = 'translateFilterFactory';
  2908. angular.module('pascalprecht.translate')
  2909. /**
  2910. * @ngdoc object
  2911. * @name pascalprecht.translate.$translationCache
  2912. * @requires $cacheFactory
  2913. *
  2914. * @description
  2915. * The first time a translation table is used, it is loaded in the translation cache for quick retrieval. You
  2916. * can load translation tables directly into the cache by consuming the
  2917. * `$translationCache` service directly.
  2918. *
  2919. * @return {object} $cacheFactory object.
  2920. */
  2921. .factory('$translationCache', $translationCache);
  2922. function $translationCache($cacheFactory) {
  2923. 'use strict';
  2924. return $cacheFactory('translations');
  2925. }
  2926. $translationCache.$inject = ['$cacheFactory'];
  2927. $translationCache.displayName = '$translationCache';
  2928. return 'pascalprecht.translate';
  2929. }));