Search code examples
javascriptangularjsangular-translate

Dynamic language selection in AngularJS


Hi I am developing one application in Angularjs. This website will be in two languages. They are arabic and english. Belo is the logic i am using for selection of language. If the browser default language is Arabic then display website in Arabic. If the browser default language is not Arabic then display website in English.

Also i have kept image(Arabic and English) on website to switch between languages.

  <div class="language"><a href="#"><img src="images/arabic.png"></a></div>
        <div class="language"><a href="#"><img src="images/en-english-language-browser-function-512.png"></a></div>

now two anchor tags are there. I am trying to bind image to anchor tag based on the language selection. I do not want 2 anchor tags.

app.controller('RoslpAppController', ['$scope', '$translate', 'toastr', '$window', function ($scope, $translate, toastr, $window) {
    debugger;
    var lang = $window.navigator.language || $window.navigator.userLanguage;
    if (lang === 'ar-sa')
    {
        $translate.use('de_AR');
         //bind arabic.png
    }
    else
    {
        $translate.use('de_EN');
         //bind english.png
    }
}]); 

I am new to the angular world. May I get some help to complete this? Any help would be appreciated. Thank you.


Solution

  • You could just store the current language in a $scope variable and use that with ng-src to set the source of the image dynamically. Like this:

    <div class="language">
        <a href="#">
            <img ng-src="images/{{ lang === 'ar-sa' ? 'arabic.png' : 'en-english-language-browser-function-512.png' }}"/>
        </a>
    </div>
    

    app.controller('RoslpAppController', ['$scope', '$translate', 'toastr', '$window', function ($scope, $translate, toastr, $window) {
        debugger;
        $scope.lang = $window.navigator.language || $window.navigator.userLanguage;
        if ($scope.lang === 'ar-sa')
        {
            $translate.use('de_AR');
             //bind arabic.png
        }
        else
        {
            $translate.use('de_EN');
             //bind english.png
        }
    }]);