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

Displaying information in ejs format

I am currently working on a project to develop a basic webpage that requires the user to input a specific time and then click on submit. Once submitted, I want the relevant data linked to that input to be displayed on the webpage. Upon clicking the submit ...

What is the best way to activate a watch upon clicking a button?

Is there a way to use the $watch() method on a button in order to trigger it when the button is pressed? Here is an example of the HTML: <button style="margin-left:10px;" class="btn btn-danger btn-xs"> Re-init tableau ...

The Implementation of Comet Programming

I'm interested in creating a web application similar to Google Docs where multiple users can edit and view changes in real-time. Would Comet Programming be the best approach for this? As a newcomer to Web Development, I'm currently learning Java ...

Malfunctioning string error in Django view caused by boolean inconsistencies

Looking to extract variables from a post request made by Javascript. Upon inspecting the received variables in my view, I found the following: >>> print request.body {"p":"testprd","cash":false,"cheque":true,"debit":false,"credit":true} The valu ...

Extra spaces within the source code visible after the page has been processed by Angular

Within my angular application, I am retrieving a list of addresses from a service that provides an object structured like this: { Flat: "10B", BuildingName: "Some Building", Line: "10B Some Building Road Town POST CODE", Postcode: "POST CODE", ...

A guide on installing a npm dependency module from a local registry domain

I have successfully published a module on my own custom registry domain, located at , and I am able to publish updates to the module there. Unfortunately, I am encountering an issue with dependencies within my published module. For example: "dependencies" ...

Loop through different JSON objects with unique values using ng-repeat

I am facing an issue with a JSON file that contains three different objects for each area, and I need some help. Here is an example: { "gebieden":"Antwerpen", "onderwerpen":"Gemiddeld netto inkomen per belastingsplichtige", "data_2005":"15084, ...

When scrolling, the selected text does not maintain its correct position

I'm looking to enable my users to search by selecting text. Once they select text, a new button will appear on the right side of the selected text giving them the option to search or not. However, when the user scrolls to the bottom of the page, the p ...

Establish a connection to couchDB using JavaScript on the server side

I'm working on a piece of code that involves using Restify to set up a server in node.js and create specific routes. My goal is to interact with CouchDB by performing actions such as GET, POST, DELETE, and PUT. var restify = require("restify"); var s ...

Encountering an issue when attempting to downgrade React Native version from 0.51 to 0.45

My current project requires me to downgrade due to certain third-party packages not being updated for the latest version of react-native. Specifically, I am using Xcode 9.0. Despite my efforts to downgrade the react-native version, I encountered the follo ...

Implementing $modal functionality within my controller

Here is the code snippet I am referring to: .js file var app = angular.module("rgMenu", ['ui.bootstrap']); app.controller("MenuController", function ($scope, $http) { ///Some code here }); Everything seems to be working fine with the ab ...

Certain CSS styles for components are missing from the current build

After building my Vue/Nuxt app, I noticed that certain component styles are not being applied. In the DEVELOPMENT environment, the styles appear as expected. However, once deployed, they seem to disappear. All other component styles render properly. Dev ...

Issues with the History API in AJAX Requests

Recently, I have come across a dynamically generated PHP code: <script> parent.document.title = 'Members | UrbanRanks'; $("#cwrocket_button").click(function(){ $("#module").load("modu ...

Troubleshooting angular.js error with ng-bind-html

I am experimenting with angular.js and trying to understand ng-bind and ng-bind-html. Here is the code snippet I am working on: <div ng-app="module" ng-controller="controller as ctrl"> <div ng-bind-html="ctrl.html"></div> </div> ...

Is it advisable to opt for window.webkitRequestAnimationFrame over setInterval?

Trying to figure out the best method for moving game characters in my JavaScript game - should I go with window.webkitRequestAnimationFrame or stick with setInterval? Any advice is appreciated! ...

Unexpected behavior occurs when ajax is added to an array for jQuery promise results

In my code, I have an each loop that makes individual AJAX requests and stores them in an array like this: var promises = []; $items.each(function(k, v) { promises.push( $.ajax({ url: ..., .... }) ); }); $.when.app ...

jQuery: Set default option selected or reset value

I'm attempting to change the value of the nearest select option dynamically. $(document).ready(function () { $('.limitation_points').hide(); $('.field .limitSelected').each(function () { $(this).change(function ( ...

Using asynchronous functions in React Native still generates a promise despite the presence of the 'await' keyword

After making an API call, my react-native component is supposed to return some SVG. Despite using an async function with await, the function still returns a promise that has not resolved yet. I have seen similar questions asked before, but I am puzzled as ...

Exploring the functionalities of the useState object with mapping techniques

While attempting to convert my class-based component to a functional style, I encountered the following code: const [foo, setFoo] = useState(null); const [roomList, setRoomList] = useState([]); useEffect(() => { setRoomList(props.onFetchRooms(props.to ...

Distribute the capabilities of the class

Is there a way to transfer the functionalities of a class into another object? Let's consider this example: class FooBar { private service: MyService; constructor(svc: MyService) { this.service = svc; } public foo(): string { ...