doshprompt / angular-localization Goto Github PK
View Code? Open in Web Editor NEWangularjs localization done right.
Home Page: http://doshprompt.github.io/angular-localization
License: MIT License
angularjs localization done right.
Home Page: http://doshprompt.github.io/angular-localization
License: MIT License
To save on bandwidth and loading costs, we can use local storage to store our language files, which will greatly speed up the second and third time users visit our application.
Config should provide an option to allow the developer to specify a localStorage module to use, and if true
use window.localStorage directly, if available.
AngularJS issues a JS warning if there is no aria-label
attribute present on certain elements
(e.g., <md-button></md-button>
)
Is there a way to prevent the warning when using something like this?:
<md-button data-i18n-attr="{'aria-label':'common.foo'}" data-i18n="common.foo"></md-button>
Wondering if it's possible to move whole pluralize staff from HTML markup to substituted strings?
The main con of the following example that developer has to know all plural cases in advance for all languages. Adding new language require html update and makes it dirty as adds more language specific cases.
<span
data-ng-pluralize
data-count=“pluralization.numCount"
data-when=“{
'0': '{{ pluralization.options.zero | i18n }}’,
'1': '{{ pluralization.options.one | i18n }}’,
'2': '{{ pluralization.options.two | i18n }}’,
‘3': '{{ pluralization.options.three | i18n }}’,
'other': '{{ pluralization.options.many | i18n }}' }”>
</span>
It would be better to simplify HTML to specify message key and optional gender/plural attributes and leave message format for a translator:
<span
data-ng-i18n="message.key"
data-gender=“gender"
data-count=“numCount">
</span>
Message itself should be able to case between genders (when necessary) and plural options specific for particular language.
Inspired by http://userguide.icu-project.org/formatparse/messages
hello i am trying to set the default local, but it's is always using 'en-US' by default.
i have to manually call local.setLocal('fr-FR') from my controller to set to the desired language and also the selection doesn't even persist!
donno if im doing it wrong since its a straight forward task. here is my implementation :
angular.module('myApp', [
'ngLocalize',
'ngLocalize.InstalledLanguages',
'ngLocalize.Events',
'ngLocalize.Config',
])
.value('localeSupported', [
'en-US',
'fr-FR',
])
.value('localeFallbacks', {
'en': 'en-US',
'fr': 'fr-FR',
})
.value('localeConf', {
basePath: 'languages',
defaultLocale: 'fr-FR',
sharedDictionary: 'common',
fileExtension: '.lang.json',
persistSelection: true,
cookieName: 'new_cookie',
observableAttrs: new RegExp('^data-(?!ng-|i18n)'),
delimiter: '::'
})
i have a language folder with sub-language folders...
and logging the local inside the controller
console.log(locale.getLocale()); always returns 'en-US', if i set it up manually by calling local.setLocal('fr-FR') the resources are updated however selection doe not persist when refreshing the browser.
persistance issue is solved by adding 'ngCookies' module to myApp
Hi, when i try to use json format like this :
{ "main": { "header": "myHeader" } }
from my template i can access this like filename.main.header, but on Network Tab (Chrome) trying to get file ../main/header.file_extension, as you can see, "main" key from json file occurs in path like directory, How can i avoid this?
I tried to use this in my http interceptor to display translatable loading messages but it throws circular dependency error. Is this a known issue? Any workaround?
i elaborate more
Suppose for default eng language i want to show "hello" to "Hi" for one user and for another "Hello".
Thanks
Hi,
Did you guys notice that when you run the tests from protractor, the localisation is not run?
E.g.
expect($(".more-button span[data-i18n='navbar.more']").getText()).toNotBe("")
This fails unfortunately, do I need to add something in beforeEach to wait for the localisation? I think that might be the problem.
Thanks for the great job :)
Michal
link: function(scope, element){
scope.labels = {};
locale.ready('radar').then(function () {
scope.labels.PLACE = locale.getString('radar.PLACE');
scope.labels.PRICE = locale.getString('radar.PRICE');
scope.labels.PROMO = locale.getString('radar.PROMO');
scope.labels.OPPORTUNITY = locale.getString('radar.OPPORTUNITY');
scope.labels.SALESDOLLARS = locale.getString('radar.SALESDOLLARS');
});
scope.$watch('labels.PLACE', function () {
if (scope.labels.PLACE!=undefined)
drawRadar();
})
I have a fairly large app in development that uses the i18n filter in angular-localization quite a bit. I was using 1.0.1 and just upgraded to 1.1.2 and the filter stopped working. The attribute directive and service still work as expected. I confirmed this behavior in the demo app included in this repository.
I stepped into the code, and it looks like the filter fires when expected and causes the language files to load from the server, but the strings are never replaced after the language file is loaded.
I also upgraded Angular to 1.3.0 at the same time, though I don't know if that matters.
Could it be possible to npm publish
this so that one can require it using npm install angular-localization
?
At the same time it should then be possible to require('angular-localization')
as well.
Is it possible to render translated texts that are in JSON arrays?
E.g. like that: http://plnkr.co/edit/n6we0O96vlSo67MDyJqs?p=preview
Such a feature is key for the applications I am building.
In latest version there was a change to browser locale detection:
b69d76b
When cookies support enabled (so "cookieStore" is defined), but cookie is not present (opened first time), it passes undefined to setLocale(value) and application fails:
value.split('-')[0].
Thanks in advance.
Does angular localization supports rtl?.I mean if i select a rtl language,the directional context of the page is shifted from right to left.
Is it currently possible to distribute resource files across multiple folders instead of placing them all under one folder off of the root path (e.g. languages/
)? We are using component based file organization and would like each component to have its own languages/
directory that we'd call i18n/
.
Hello,
in many of our projects (java, flex, js...) we use the nlstools (https://code.google.com/p/nlstools/) to manage the localization texts, to convert them between xml, excel (to let customer edit them), merge/add locales, validate/find missing translations, compare and generate .json, .java, ... files from it.
We are using angular-localization in our current projects. nlstools also support the .json format required by angular-localization. Maybe it's worth mentioning this because it might also be helpful for other users.
https://code.google.com/p/nlstools/ has the source and an example project to show the usage and integration. The libs are available on maven-central. Current version 2.6 supports angular-localization and can generate compact .json or pretty formatted .json files from excel/xml.
Thanks for angular-localization!
Bye,
Roman
module compat with angular2 and/or rollout new fork ng2-localization
Hi Rahul. I've really enjoyed your talk at Google AngularJS Meetup (just couldn't tell what city this was in). I believe you've mentioned willingness to migrate from Grunt to Gulp.js build. Is this something you are still interested in?
I'm using the parameterized substitution of strings, using {1}, {2}.
The project uses same resource files for angular and ASP.NET C#, and it starts the index on {0}. This will cause confusion and inconsistencies between resources used on both sides.
Is there a way to make angular-localization use 0 based substitutions?
it reports an error while loading language resources which is
Error: The resource is a direct reference to a non-default resource candidate.
thanks!
I was thinking about ng-pluralize and angular-localization in the case where we have a phrase that is translated into two languages with different number of plural modes.
E.g., in english, we just want to use the simple rule one / other:
<ng-pluralize data-count="numCount" data-when="{ '1': '{{ 'one': '{{ plurals.one | i18n }}', 'other': '{{ plurals.other | i18n }}' }" ></ng-pluralize>
But if I then want translate to, say, russian, then the number of rules i need changes to 4 to something like:
<ng-pluralize data-count="numCount" data-when="{ '1': '{{ 'one': '{{ plurals.one | i18n }}', 'other': '{{ plurals.other | i18n }}', 'few': {{ plurals.few | i18n }}, 'many':'{{ plurals.many | i18n }}' }" ></ng-pluralize>
However, I've already hardcoded the number of rules by setting them in the when
attribute as such, so just translating the one
and other
options from the english version isn't enough to implement the above.
So, what I'd really like to so is something like:
<span data-count="numCount" data-i18n-plural="pluralMsg"></span>
And then provide, in the translation for pluralMsg
, a plural-sensitive string. This is the way it's handled in ICU format (e.g. formatjs and I can see why -- it makes a lot more sense to have the translator figure out the correct pluralization rules in the yaml/json file then to have devs set the plural branching.
This leads me to few questions:
Thanks!
Hi,
Is it able to use data-i18n directive or filter to localize ng-message? it does not work like this. appreciate for suggestions in advance.
<md-input-container>
<label data-i18n="login.username"></label>
<input type="text" ng-model="ViewData.UserName" name="UserName" required />
<div ng-messages="loginForm.UserName.$error">
<div ng-message="required" data-i18n="common.required">This is required.</div>
</div>
</md-input-container>
Currently, angular-localization depends on an external repository to release its dependencies. The distribution was external, so angular-localization's install could be as small as possible. But this decision come with extra release complexities, so it was decide to deprecate bower-angular-localization.
Thanks to @bretmorris for initial PR to get the ball rolling!
Fixing angular-localization release will be done in 2 parts.
bower_components/angular-localization/angular-localization.js
.
Although the angular-localization project will be large on install, the module will have all the necessary project files.
Is anyone still using this?
For best compatibility, the distributions files will be located at bower_components/angular-localization/
and bower_components/angular-localization/dist
.
Please make "key not found" behavior configurable.
For example, I'd like to see the missing key instead of not very helpful %%KEY_NOT_FOUND%%
Closed in 1e4b0bf but forgot to add to footer of commit.
Hi there,
Excellent job for the module. I have one question regarding key usage - in your example the key is always one word string e.g. 'helloWorld'. However, I used to have json file with pairs (key and value), coming from SailsJS locale and the are:
{
"Hello World": "Hello World",
"Bye World": "Bye World"
}
So my question is - Is it possible to invoke i18n
in html code with such a key and if 'yes' what is the format? I was trying like <h2 class="section-heading" i18n='home."Instant Call"'></h2>
, but it doesn't seem to work...
Thanks
Firstly, I have to say this is a really awesome project, love it!
a few suggestions about language choose and persist.
I was wondering if it's possible to load the supported locales from a remote REST service. I have to define supported languages there as well so I wanted to be able to do it once. I'm just not sure how to go about setting the localeSupported value that way or if it would work at all.
Just add the site, http://doshprompt.github.io/angular-localization/, to make it more discoverable.
For now we can use interpolation like so:
Specifically I tried to setup 'es-AR' language fruitlessly. I couldn't find a way to do it even using this piece of code:
angular.module('myApp', [
'ngLocalize',
'ngLocalize.Config'
]).value('localeConf', {
basePath: 'languages',
defaultLocale: 'en-US',
sharedDictionary: 'common',
fileExtension: '.lang.json',
persistSelection: true,
cookieName: 'COOKIE_LOCALE_LANG',
observableAttrs: new RegExp('^data-(?!ng-|i18n)'),
delimiter: '::'
});
So that, I dug into the code and I found that defaultLocale
is being ignored in favor of cookie value (COOKIE_LOCALE_LANG). Here:
https://github.com/doshprompt/angular-localization/blob/master/src/localization.js#L250
If the cookieStore is already defined then the defaultLocale
is ignored because cookie value is grabbed. Supposing the cookie value is undefined then windows properties are used.
Even if I deleted the cookie the used value would be windows properties values.
This code is intended to do that. If so, there is a way to setup the language for the whole angular app?
Thanks a lot in advance
Need to think about this one, whether it's needed or overengineering, Also, How to support it in the most extensible manner.
Hi.
Thank you for the great library.
It's great that library tries to follow Language Culture Name specification by Microsoft, but it is bad for people making chrome extensions.
Look at the locale table from chrome
They don't support Culture Names like fr-FR or ru-RU or whatnot.
That leaves me no option but to create separate folders like
So can you leave option of just passing 'en' and 'ru' and 'fr'?
Previous version of this library was supporting it out of the box, don't know how this version handles it...
Sorry if I am missing something, in that case can you point me to how can I do it otherwise of making separate folders...
It's simple, with this :
{
"test" : "Ca marche !"
}
$scope.strings = [];
locale.ready('common').then(function () {
$scope.strings.test = locale.getString('common.test');
});
.value('localeConf', {
basePath: 'languages',
defaultLocale: 'en-US',
sharedDictionary: 'common',
fileExtension: '.lang.json',
persistSelection: true,
cookieName: 'language',
observableAttrs: new RegExp('^data-(?!ng-|i18n)'),
delimiter: '::'
})
.value('localeSupported', [
'en-US',
'fr-FR',
])
.value('localeFallbacks', {
'en': 'en-US',
'fr': 'fr-FR'
})
I can do this :
<ul>
<li i18n="common.test"></li>
<li><input data-i18n-attr="{placeholder: 'common.test'}" /></li>
<li>{{strings.test}}</li>
</ul>
But not this :
<ul>
<li>{{ 'test' | i18n }}</li>
<li>{{ test | i18n }}</li>
<li>{{'common.test' | i18n}}</li>
<li>{{common.test | i18n}}</li>
<li ng-bind="common.test | i18n"></li>
<li ng-bind="'common.test' | i18n"></li>
</ul>
Love the framework, excellent job.
I have a question about the fallback locale.
I have an en-GB set of lang.json files which work just great.
I want begin to create an ar-AE locale, but so far I have just done one lang.json file.
However, what I would expect is that if the getString cannot find a bundle for this locale, it should use the fallback locale to try and find the token.
If not, it means that I must add tokens to each language when I add a new string, otherwise they will read %%KEY_NOT_FOUND%% rather than the fallback language, english.
Do you have a change in the works for this?
Hi there,
I have currently two cases, where I need some assistance:
Tag content replacement:
Lets suppose I have html snippet like below, which requires localization:
String requires Localization
I have noticed that using i18n
directive actually replaces the whole tag content, so in my case the <i>
will be removed.
How can I solve that?
"My Product Name"
and "beta version"
. So I want to use them:"{name} {version}"
and then pass to this string both other strings. So how can I do that using i18n
directive? I considering usage of data-i18n
directive, but it is not clear how I can pass to data-name
parameter another localized string.In the doc it says
If you want to pass dynamic values for the string, those should come after the value for each key; the series of additional parameters is expected to be appendeded to the token, prepended with a separator so that the directive will walk through and replace the numbered place holders with their values.
What does prepended with a separator
mean? Can you provide an example?
Thanks
just update bower.json file in the project by changing 1.2.x to 1.3.x to 1.4.x, the demo page will not work.
Is there a way to access resource strings using object properties / keys instead of passing strings?
I've tried to get access to the resource bundle, but the variable is private, so I cannot even iterate to obtain list of keys.
This would make the code more readable, better syntax, and color coding in my text editor would be able to differentiate from regular strings in the code.
How I use today:
var resourcePath = 'Document.Create';
locale.getString(resourcePath + '.New');
How I would like to use:
var resDocCreate = locale.keys('Document.Create');
locale.getString(resDocCreate.New);
What is the best practice using ngLocalize to provide different translations based on gender? Afaik, the current approach is to use ng-switch on a gender key, which, as #16 identifies, suffers from the issue that potential gender disparities have to be taken into account by the html author, not just the translator.
I think the main
attribute in bower.json
needs to be updated to [ "dist/angular-localization.js", "dist/angular-localization.css"]
Some build tools rely on this attribute to dynamically inject dependencies.
Hello,
is there support for AngularJS 1.3, if there is, the bower file should be updated.
add if (deferrences[path]) {
deferrences[path].reject(data);
}
to:
$http.get(url)
.success(function (data) {
var key,
path = getPath(token);
// Merge the contents of the obtained data into the stored bundle.
for (key in data) {
if (data.hasOwnProperty(key)) {
root[key] = data[key];
}
}
// Mark the bundle as having been "loaded".
delete root._loading;
// Notify anyone who cares to know about this event.
$rootScope.$broadcast(localeEvents.resourceUpdates);
// If we issued a Promise for this file, resolve it now.
if (deferrences[path]) {
deferrences[path].resolve(path);
}
})
.error(function (data) {
$log.error("[localizationService] Failed to load: " + url);
if (deferrences[path]) {
deferrences[path].reject(data);
}
// We can try it again later.
delete root._loading;
});
Hi there... I've been having an issue: I've been saving twice my information in my database because I want support my website in multiple languages. I'm making an admin panel so the person that wants the website can change content. The admin wants to publish himself the translation of every post on the website. I don't have total control over my REST service (I'm using deployd).
These are my columns in the same table
id | titleEN | titleES | titleCA ... etc...
How can I do it?
Thanks.
P.D.: Great job on angular-localization. I've been really using it.
should let strings pass through similar to the filter.
For small apps it will be better if they can bundle their dictionaries with the source code at build time (using grunt or gulp) and set them directly and synchronously when the app loads. Instead of having to make another trip to the server to get the dictionaries.
Something like this;
app.config(function (locale, $window) {
locale.loadBundle('common', 'en-US', $window.__languages['en-US'].common);
locale.loadBundle('common', 'fr-FR', $window.__languages['fr-FR'].common);
});
Thoughts?
Thanks
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.