Reputation: 465
I'm currently building a multilingual AngularJS app. All my data is retrieved from api which returns the correct languages. The problem is. Currently I'm using a $scope
for every button, every thing in the app. Is this the best way or is there a way to call this directly from a view.
For example:
{{datakey.get.test}}
Some application specific info:
I get the data once (when loading the app) from the api. As a $http I currently retrieve the data and then for each scope I do this:
For example the select button:
$scope.selectButton = resourceKey.filter(function (item) {
return item.name === prefix + "select-button"
})[0].value;
Then in the view I call {{selectButton}}
But the problem is. My controller is currently getting spammed with these kinda $scopes.
Can this be done more efficiently?
Upvotes: 0
Views: 66
Reputation: 44715
Another option is to use filter instead of directive:
.filter('translate', function (localeKeys) {
return function(input) {
return localKeys[input] || 'Missing translation for' + input;
};
});
# View
{{ 'translation.key' | translate }}
Upvotes: 1
Reputation: 6958
If the keys are all known and retrieved from an API, you can write a directive to do the replacement for you and won't have to clutter your scope. As an exercise, I've left variable arg replacement (e.g the {0} in "You have selected {0} items") unimplemented... In any case, you should avoid a watch when the value is static/doesn't change.
angular.module('myApp', [])
// Mocking these out, assuming they would come from API and be set in
// key: value manner
.value('localeKeys', {
'datakey.get.test': 'Testing 1',
'datakey.select-button': 'Select'
})
// Simple lookup
.directive('appTranslate', function (localeKeys) {
return {
restrict: 'AE',
link: function (scope, elem, attrs) {
var attr = attrs.appTranslate,
translated = localeKeys[attr] || attr || '';
elem.html(translated);
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<h3 app-translate="datakey.get.test"></h3>
<button type="button" app-translate="datakey.select-button"></button>
</div>
The above sample simply looks up the value provided to the directive in the localeKeys. You would swap these localeKeys with the values you retrieve from your API.
Upvotes: 2
Reputation: 22697
Because you are fetching static data(you wont change button names), you can bind your button name in one-way binding avoiding the overhead, just use ::
this tells angular that DONT'N put a $watch over that expression to see if there is any change.
{{::datakey.get.test}}
Upvotes: 0