The Angular translation function is being called repeatedly without end

I have a function that performs text translation. It is hooked to all the text elements and appears as follows:

$rootScope.translateText = function (key) {
  if (angular.isDefined(Language.dictionary[key])) {
    return Language.dictionary[key];
  }
  return key;
};

This is how it is connected in a view:

<h1 style="text-align: center">{{translateText('Name')}}</h1>

The issue I am facing is that translateText is being called indefinitely, even with only one instance per view, leading to a loop.

The language can be switched at any time.

What mistake am I making and what is the solution?

Answer №1

The binding you are utilizing ({{getWord('Name')}}) undergoes evaluation during each iteration of the digest loop. When considering the number of getWord calls on a single page...

To address this issue, consider using a "single-time binding":

<h1 style="text-align: center">{{::getWord('Name')}}</h1>

An expression starting with :: is recognized as a one-time expression.
One-time expressions cease reevaluation once they stabilize, typically after the first digest if the result is a non-undefined value.

If your intention is to facilitate text rebinding, an alternative approach can be taken:

<h1 style="text-align: center">{{translated.Name}}</h1>

In your controller, populate a $scope.translated object with all the necessary translations.
You can enable the translation function to be triggered again in case of a language switch, similar to the following:

$scope.translate = function(keys){
    someTranslationWebService.get(keys, function(response){
        $scope.translated = response;
    });
};

keys can be represented as an array such as:

['Name', 'CompanyName', 'Address']

The expected format for response is as shown below:

{
    "Name": "Recipient's name",
    "CompanyName": "Company name",
    "Address": "Delivery address"
}

Alternatively, you could explore the use of the "angular-translate" library

Answer №2

Consider utilizing a filter instead, like this:

<h1 style="text-align: center">{{ Name | customFilter}}</h1>
angular.module('yourApp')
  .filter('customFilter', ['Language', function(Language) {
    return function(key) {
      return Language.dict[key] || key;
    };
  }]);

Answer №3

One possible solution is to:

 var Language = {dict: {Name: 'Name 1'}};
    $scope.visited = [];
    $rootScope.getWord = function(key) {
        if (angular.isDefined(Language.dict[key])) {
            $scope.visited[key] = Language.dict[key];
            return Language.dict[key];
        }
        $scope.visited[key] = key;
        return key;
    };

Additionally, you can display the word using the following code snippet:

<span style="text-align: center">{{visited['Name']?visited['Name']:getWord('Name')}}</span>

Remember to reset the visited object when the language changes.

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

Ensure all asynchronous Ajax requests have completed before considering the page fully loaded

Many websites, such as YouTube, load the majority of their content after the DOM is ready using JavaScript. How can I ensure that all of these requests have been completed before injecting my code? window.onload = function() {}; The above code snippet do ...

VueJS 3 custom Checkbox fails to update UI upon clicking

I'm attempting to implement a customized checkbox using Vue 3 and the composition API based on this example. However, despite confirming through devtools that all my props and bound data are successfully passed from the parent component to the child c ...

Tips for managing image uploads while incorporating pre-set error detection into a form

I'm facing a challenge with integrating an optional image upload feature into my express app. The issue seems to be related to the way I've structured the app, as it appears to be trying to pass the image name from the body instead of utilizing t ...

Connect or disconnect an element to a JavaScript event handler using an anonymous function

I'm stuck on a basic issue... I have a custom metabox in my WordPress blog, and here's my event handler: jQuery('tr input.test').on('click', function( event ){ event.preventDefault(); var index = jQuery(this).close ...

I would prefer not to add another database table just to differentiate between team members and friends. Can you provide assistance with this?

Instead of creating another table named friends in Strapi and linking it to Visual Studio Code, I have opted to use a Characters table for both team members and friends. This way, I can input new data only at Characters and filter it to differentiate betwe ...

Plugin for creating a navigation bar with a jQuery and Outlook-inspired style

Our team is considering transitioning our asp.net forms application to MVC. Currently, we utilize outlook-style navigation with ASP controls such as listview and accordion, using code referenced here. Are there any jQuery/CSS controls available for MVC t ...

React NextJS: Unable to retrieve cookies or properties post redirection

Within my nextJS application, when a user logs in on the login page, a cookie is created with a token and then they are redirected to the main page which utilizes the main component. However, within the Main component, I am encountering an issue where the ...

Formatting numbers as floating point values in AngularJS

I need a text box where users can enter an amount. The input should be restricted to numbers only, with no special characters or decimal points. I have managed this using custom filters. However, I also need the entered number to automatically display as ...

Having difficulty asserting the dual-function button in both its disabled and enabled states

I have a button that is part of a dual-action setup. This button is disabled until a certain event occurs. Here is the DOM structure while the button is disabled: <div class="doc-buttons"> <a href="#" onclick="actualsize();" id="tip-size" cla ...

Experience the enhanced features and optimized performance of Onsen 2.0 compared to the earlier version

Apologies if this question is too simplistic, but I am finding some conflicting information in the documentation about using Onsen with Monaca. I am currently utilizing Monaca cloud and I prefer to work solely with pure JS, without incorporating Angular ...

Utilizing Selenium to inject javascript permanently or on every page refresh

In my selenium webdriver test using Python 3, I have implemented a semi-automated process. This means that some routines are automated while other tasks require user interaction with the browser, such as page refreshes or redirects. My challenge is to inj ...

Unexpected loading glitches occurring in vue-material components

I recently delved into the world of Vue.js and VueMaterial, which has been a refreshing and new experience for me since I've mostly focused on Native Android development in the past. Currently, I'm facing an unusual issue that seems to stem from ...

Aligning the stars with CSS

One of the components I have deals with a star rating system, and I thought it would be cool to use Font Awesome icons for half stars. Everything is working well except for the CSS styling aspect. While I managed to position some of the stars correctly by ...

What is the process for executing code on a server by clicking a button?

In my Next.js application, there is a file named dummy.js with the following content: class Dummy extends React.Component{ static async getInitialProps(ctx){ return { dummy : 'abc'}; } displayHelloWorld(params) { cons ...

Having trouble accessing the property of undefined in material ui cards

Currently, I am incorporating Material UI cards into my React project. One issue I encountered is trying to implement two functions, onMouseOver and onMouseOut, in my cards. However, when I run the code, I receive an error message stating "Uncaught TypeE ...

What is the significance of `(<typeof className>this.constructor)` in TypeScript?

After inspecting the source code of jQTree, written in Typescript, available at https://github.com/mbraak/jqTree, I came across the following snippet: export default class SimpleWidget{ protected static defaults = {}; ...

Determine the vertical distance that a div element is currently visible while scrolling

To better understand this concept, please refer to the following fiddle: http://jsfiddle.net/abhicodes/LasxP/ The main goal here is to calculate the visible height of the element with the ID #content-wrapper as the user scrolls. The height of the header ( ...

Utilizing Javascript to implement a tooltip feature for dynamically inserted text

I recently incorporated a brief jQuery tooltip plugin into my site. It consists of approximately ten lines of code and works smoothly, as demonstrated in this demo. However, I encountered an issue when attempting to add new text that should also trigger t ...

What sets Protractor apart from Grunt?

According to the Protractor website (http://www.protractortest.org/#/infrastructure), Protractor utilizes Selenium for browser automation. However, when browsing through the Grunt website (http://gruntjs.com/), it's mentioned that Grunt is also used f ...

Customize data appearance in Django Admin interface

I am working with a model that has a json field. The data stored in this field may not always be pretty-printed, and I am okay with it as long as it is valid. However, when the data is displayed in Django admin, I would like it to be pretty printed for eas ...