JSFiddle : http://jsfiddle.net/X2fsw/2/
I try to create a multilingual AngularJS application using angular-translate.
I have a static list of items embedded in my code.
Each item of this list has a title, and that title has to be displayed in the currently selected language.
Translations are done directly in the view with the help of the translate service.
Example: {{ myObject.title | translate }}
.
I wish to display the list using ng-repeat
, then filter it by item title.
However, the filter is applied on the translation key, not on the translated string.
What would be the best way to correct this behavior while keeping the ability to switch language at runtime?
I could store the translated string as another property (eg. myObject._title
) on every language change, but my list wouldn't be a constant anymore.
What do you recommend?
The ng-repeat values can be filtered according to the ng-model in AngularJS by using the value of the input field as an expression in a filter. We can set the ng-model directive on an input field to filter ng-repeat values.
Each ng-repeat creates a child scope with the passed data, and also adds an additional $index variable in that scope. So what you need to do is reach up to the parent scope, and use that $index . Save this answer.
AngularJS supports i18n/l10n for date, number and currency filters. Localizable pluralization is supported via the ngPluralize directive. Additionally, you can use MessageFormat extensions to $interpolate for localizable pluralization and gender support in all interpolations via the ngMessageFormat module.
AngularJS ng-repeat Directive The ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object. Note: Each instance of the repetition is given its own scope, which consist of the current item.
I would consider writing a custom filter. This ist described here: http://docs.angularjs.org/guide/filter. In the custom filter you could use the $translate service translating your keys to the translated string (http://pascalprecht.github.io/angular-translate/docs/en/#/guide/03_using-translate-service)
so based on your fiddle:
myApp.filter('translateFilter', function($translate){
return function(input, param){
if(!param){
return input;
}
var searchVal = param.key.toLowerCase();
var result = [];
angular.forEach(input, function(value){
var translated = $translate(value.key);
if(translated.toLowerCase().indexOf(searchVal)!==-1){
result.push(value);
}
});
return result;
};
});
usage:
<li ng-repeat="day in days | translateFilter:search">
{{ day.key | translate }}
</li>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With