Choosing different languages on the fly with AngularJS

Hey there! I'm currently working on an Angularjs application that will be available in both Arabic and English. Below is the logic I have implemented for selecting the language: If the browser's default language is set to Arabic, then the website will display in Arabic. If the browser's default language is not Arabic, then the website will display in English.

In addition, I have included images (one for Arabic and one for English) on the website to allow users 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>

Currently, there are two anchor tags present. I am working on binding the image to the anchor tag based on the selected language, but I would prefer to have only one anchor tag.

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 fairly new to the world of Angular development. Can anyone provide some guidance on how to accomplish this task? Any assistance would be greatly appreciated. Thank you!

Answer №1

The issue does not lie with the controller and it is not recommended to use the controller for language selection.

Instead, utilize the configuration phase for language settings, similar to the following example:

app.config(function($translateProvider) {
  $translateProvider.translations('en', {
    HEADLINE: 'Greetings, Welcome to my amazing application!',
    INTRO_TEXT: 'It also supports internationalization!',
    BUTTON_TEXT_EN: 'english',
    BUTTON_TEXT_DE: 'german'
  })
  .translations('de', {
    HEADLINE: 'Hallo, Willkommen zu meiner großartigen Anwendung!',
    INTRO_TEXT: 'Und sie unterstützt Mehrsprachigkeit!'
    BUTTON_TEXT_EN: 'englisch',
    BUTTON_TEXT_DE: 'deutsch'
  });
  $translateProvider.preferredLanguage('en');
});

Answer №2

To dynamically set the source of an image based on the current language, you can store the language in a $scope variable and use ng-src accordingly. Here's an example:

<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
    }
}]);

Answer №3

To ensure your website supports both English and Arabic languages, you can utilize two JSON files. Each file should contain the same keys with different values. For example:

For English

[
             "title":"Website",
             "img": "provide the image source path for English"
            ]

For Arabic

[
            "title":"Website(Arabic Translation)",
            "img": "provide the image source path for Arabic"
           ]

Incorporate these files using

$translateProvider.useStaticFilesLoader
along with
angular-translate-loader-static-files
, which can be obtained from bower or npm.

Finally, reference your images like this:

<img src={{img}}/>

That's all there is to it!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to notify the JSON code below using jQuery?

I have received a JSON response after using the Reverse Geocoding API from Google. The response includes various address components such as route, sublocality, locality, and political information. { "results": [ { "address_components": [ ...

Utilizing Express JS and Discord JS to assign roles

Hello there, I'm currently working on assigning a role to a user through a post request using the express framework. However, I'm facing some difficulties as I usually handle this process through the message function. Below is the code snippet: ...

Differences between ClosureFeedbackCellArray and FeedbackVector in the V8 engine

Can you explain the distinction between ClosureFeedbackCellArray and FeedbackVector within V8? What steps are necessary to initiate the shift from ClosureFeedbackCellArray to FeedbackVector? What is the significance of the InterruptBudget attribute found ...

Best practices for showing the SVG element stored in a variable

Encountering an issue with displaying an SVG element stored within a JavaScript variable. The unique situation demands that the SVG is retrieved from the backend as a string value. Upon receiving the response, the SVG data is stored like so: let svgValue ...

Difficulty with Nuxt + Vuex: Retrieving data from state using getter

Can anyone assist me with this issue? I am having trouble with my getters in Vuex not recognizing the state. Here is the code snippet: https://codesandbox.io/s/crazy-moon-35fiz?file=/store/user.js user.js: export const state = () => ({ user: { is ...

Angular - ensuring an input field must be filled out

As someone unfamiliar with Angular, I find myself needing to create a required input form in an Angular application. Can anyone confirm if this is the correct approach? I simply included required="{{'required'}}" within the input tag: ...

Exploring the multi-page game interface in Asp.net - Seeking advice and direction

I am in the process of developing the game page for my quiz project using asp.net. I have already implemented all the game logic on the server-side. The game is a quiz that involves user response timing, scoring based on correct answers and timing. It is ...

Updating the state of a nested array using React Hooks

After spending some time working with React Hooks, my main struggle has been dealing with arrays. Currently, I am developing a registration form for teams. Each team consists of a list of players (an array of strings). The goal is to allow users to add t ...

Verify if the value of localStorage matches the specified value, then conceal the element

This is my second query and I'm hoping it covers everything. My knowledge of javascript is limited, which has made it difficult for me to get my code working properly. Despite trying various different approaches, I have been unable to resolve the issu ...

Utilizing AngularJS to invoke a jQuery plugin

Currently, I am utilizing the fullCalendar jQuery plugin alongside AngularJS. My goal is to call the refetchResources function of the jQuery plugin from Angular. I attempted to achieve this using the following code: angular.element(document.querySelector ...

Looking to personalize the MUI - datatable's toolbar and place the pagination at the top?

I successfully managed to hide the toolbar icon, but I am struggling with positioning pagination from bottom to top. Additionally, I am attempting to add two buttons (reset and apply) in the view-Column toolbar without any success in customizing the class. ...

Can the memory consumption of a JavaScript variable be determined?

Currently focused on Frontend development with React and Javascript. I am eager to discover if there is a method to retrieve the memory usage of a JavaScript variable, especially for objects and non-primitive values. My investigation in Chrome Dev Tool d ...

Ways to separate a form's logic within Angular applications

At times, forms can have unique logic such as requesting additional data via ajax, reading cookies, or implementing special filters. I am interested in finding a way to separate this logic from the controller and keep the HTML for the forms in a separate f ...

Please ensure there is space reserved for the header above the content

Currently, I am working on creating a webpage with a unique banner design. My goal is for the content to scroll from the bottom and remain fixed directly under the upper portion of the banner. Initially, my idea was to have the content box take up the siz ...

`Open PhotoSwipe to view the image in a new window`

My goal is to open the current visible photo in a new window using JavaScript, while ensuring it works on an iPad as well. To achieve this, I added a button to the toolbar (similar to the example) and included its corresponding CSS in the photoswipe.css fi ...

Examining a feature by solely utilizing stubs

I've been immersed in writing tests for the past few weeks. In my workplace, we utilize Mocha as our test runner and Chai for assertions, with Sinon for creating stubs. However, there's a recurring issue that's been bothering me. I've w ...

Is the HTML5 type of button functioning properly, while the type of submit is not working as

Looking to validate a form before running a JavaScript function? Check out this code snippet: function updateMap() { //dummy } <form> <div class="group"> <input type="number" id="hour" min="0" max="23" required> <span cl ...

Incorporate socket.io into multiple modules by requiring the same instance throughout

I am feeling a bit lost when it comes to handling modules in Node.js. Here's my situation: I have created a server in one large file, utilizing Socket.io for real-time communication. Now, as my index.js has grown quite big, I want to break down the ...

Setting up jsdoc on a computer with slow internet access can be a bit tricky, but with

Recently, I have been working on some JavaScript code and utilized the sublime jsdoc plugin for commenting. Now, my goal is to generate documentation from these comments. The challenge lies in the fact that I am developing this JavaScript on a machine loca ...

Updating a hidden checkbox in an HTML input: A step-by-step guide

Currently, I have an HTML input page set up to input scores into a grid. status valueA valueB checkboxA checkboxB 1 4 5 2 x x 2 3 3 1 x 3 5 7 2 4 ...