Reputation: 2175
Hi I am developing Angularjs application. I have dynamically generated anchor tag. In anchor tag i am binding img only. So based on the img src clicked i want some computations.
<div class="language">
<a href="#">
<img ng-src="images/{{ lang === 'ar-sa' ? 'arabic.png' : 'en-english-language-browser-function-512.png' }}" />
</a>
</div>
This is my controller code.
if ($scope.lang === 'ar-sa')
{
$translate.use('de_AR');
}
else
{
$translate.use('de_EN');
}
Whenever i click on img i want to get that img name in controller. So that i can apply some computation like if use clicked on arabic.png then i can covert page to arabic. Any help would be appreciated. Thank you.
Upvotes: 2
Views: 939
Reputation: 12025
What you need to do is to add a function that change the language on the controller:
$scope.lang = null; // Default language
$scope.changeLanguage = function() {
$scope.lang = $scope.lang == 'de_AR' ? 'de_EN' : 'de_AR'; // Change the language based on the current selected
$translate.use($scope.lang);
}
$scope.changeLanguage(); // Set language when the controller loads
Next, in your view, you just need to call this function:
<div class="language">
<a href="#" ng-click="changeLanguage()">
<img ng-src="images/{{ lang === 'de_AR' ? 'arabic.png' : 'en-english-language-browser-function-512.png' }}" />
</a>
</div>
As an alternative, you can also pass the selected language:
$scope.changeLanguage = function( lang ) {
$scope.lang = lang;
$translate.use($scope.lang);
}
$scope.changeLanguage('de_AR');
And in the view:
<div class="language">
<a href="#" ng-click="changeLanguage(lang === 'de_AR' ? 'de_EN' : 'de_AR')">
<img ng-src="images/{{ lang === 'de_AR' ? 'arabic.png' : 'en-english-language-browser-function-512.png' }}" />
</a>
</div>
Edit:
Since your default language is based on browser setting, you can do the following:
$scope.changeLanguage = function( lang ) {
$scope.lang = lang === 'ar-sa' ? 'de_AR' : 'de_EN';
$translate.use($scope.lang);
}
$scope.changeLanguage($window.navigator.language || $window.navigator.userLanguage);
View:
<div class="language">
<a href="#" ng-click="changeLanguage(lang === 'de_AR' ? 'de_EN' : 'ar-sa')">
<img ng-src="images/{{ lang === 'de_AR' ? 'arabic.png' : 'en-english-language-browser-function-512.png' }}" />
</a>
</div>
What I did in the above example is to check if the language (Which is the returned value of $window.navigator.language || $window.navigator.userLanguage
) is equal to 'ar-sa'
and if so, set the language to its matching i18n code.
Upvotes: 1