$locale
is an AngularJS service that provides localization (i18n) support.- It defines date, number, and currency formats specific to a region.
- AngularJS includes default locale settings but allows customization for different languages.
How $locale
Works
The $locale
service contains:
- Date/Time Formats (
DATETIME_FORMATS
) - Number Formats (
NUMBER_FORMATS
) - Currency Symbols (
CURRENCY_SYM
) - Pluralization Rules
Example: Default $locale
for en-us
{
"id": "en-us",
"DATETIME_FORMATS": {
"AMPMS": ["AM", "PM"],
"DAY": ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
"MONTH": ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
},
"NUMBER_FORMATS": {
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"CURRENCY_SYM": "$"
}
}
Example 1: Accessing $locale
in a Controller
var app = angular.module("myApp", []);
app.controller("LocaleController", function ($scope, $locale) {
$scope.localeID = $locale.id;
$scope.currencySymbol = $locale.NUMBER_FORMATS.CURRENCY_SYM;
$scope.dateFormats = $locale.DATETIME_FORMATS;
});
Explanation:
- Fetches the locale ID (
en-us
by default). - Retrieves the currency symbol (
$
). - Displays the date formats.
Example 2: Changing Locale Dynamically
Step 1: Include AngularJS Locale Files
Load locale files from angular-i18n (e.g., angular-locale-fr-fr.js
for French).
<script src="angular-locale-fr-fr.js"></script>
Step 2: Change Locale in Controller
var app = angular.module("myApp", ["ngLocale"]); // Add ngLocale module
app.controller("LocaleController", function ($scope, $locale) {
$scope.locale = $locale.id;
});
Now the app supports French formats when the locale file is included.
Example 3: Formatting Numbers & Dates Using Filters
<p>Currency: {{ 1000 | currency }}</p>
<p>Number Format: {{ 1234567.89 | number }}</p>
<p>Date Format: {{ today | date:'fullDate' }}</p>
Filters auto-adjust based on the $locale
settings.
Best Practices for AngularJS Internationalization
✔ Use $locale
for built-in date and number formats.
✔ Load external locale files (angular-i18n
).
✔ For dynamic translation, use angular-translate
.