Skip to content

Instantly share code, notes, and snippets.

@iammerrick
Created May 4, 2013 22:10
Show Gist options
  • Save iammerrick/5518936 to your computer and use it in GitHub Desktop.
Save iammerrick/5518936 to your computer and use it in GitHub Desktop.
Angular.js + MessageFormat.js
{
"greet" : "Hello",
"messages" : "You have {count} {count, plural, one{message} other{messages}}."
}
<script>
angular.module('MyApp').controller('MessageCtrl', function(){
$scope.count = 5;
});
</script>
</script>
<div ng-controller="MessageCtrl">
<div>{{'greeting' | _ }}</div>
<div>{{'messages' | _ : { count: count } }}</div>
</div>

MessageFormat.js

Message format allows us to compile or MessageFormat JSON files to optimized JavaScript functions. (Think Handlebars precompilation.)

Compiling the file "en.json" through MessageFormat becomes a JavaScript object under the "i18n" namespace where each object property is function that can be invoked.

// Create a filter that calls into the i18n service, this would also likely call into
// a user service to decide which locale to reference.
angular.module('MyApp', [])
.filter('_', function(i18n) {
return function(key, data) {
return i18n['en'][key](data);
}
});
// Simply return the global i18n object provided by MessageFormat.js
angular.module('MyApp').service('i18n', function() { return i18n; });
-----------
Hello!
-----------
You have 5 messages.
-----------
*******
The count was evaluated on the $scope and passed into MessageFormat for pluralization, the select works well with gendering messages as well. Not to mention we have positional interpolation (which the values can be dynamic or literal thanks to angular expressions.)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment