AngularJS factory or filter failing to update properly

I have been working on a system that manages translations in my factory. I set the language as a string and then use a filter to update the view when the language changes.

Everything works fine if I define the language in the view beforehand, but when I try to change the language using a button click, nothing happens.

Can someone please help me figure out what I might be doing wrong?

This is a snippet of my view:

<div ng-app="testApp">
  <div ng-controller="myController">
    <p >{{ data.title | translate }}</p>
    <p >{{ data.text }}</p>
    <button type="button" ng-click="changeLanguage('en')">English</button>
    <button type="button" ng-click="changeLanguage('sl')">Slovene</button>
  </div>
</div>

This is part of my script:

angular.module('langService', [])
  .factory('Language', function() {
  var currentLanguage = 'en';

  return {
    setCurrentLanguage: function(value) {
      currentLanguage = value;
    },
    getCurrentLanguage: function() {
      return currentLanguage;
    }
  }
});

var testApp = angular.module('testApp', ['langService']);

testApp.controller('myController', function ($scope, Language) {
  $scope.data = {
    title: 'PAGE_TITLE',
    text :'some random page text'
  };

  $scope.changeLanguage = function(value) {
    Language.setCurrentLanguage(value);
  }
});

testApp.constant('Translations', {
  en: {
    'PAGE_TITLE': 'Hi!'
  },
  sl: {
    'PAGE_TITLE': 'Živjo!'
  }
});

testApp.filter('translate', function(Translations, Language) {
  return function(input) {
    return Translations[Language.getCurrentLanguage()][input] || '';
  };
});

I've put together an example on codepen to test it out before incorporating it into a project.

Any assistance would be greatly appreciated.

Answer №1

A stateful filter is generally not recommended, but there are valid use cases like yours that require periodic re-evaluation on the digest loop. In order to indicate that your filter is stateful, it needs to be appropriately "marked."

testApp.filter('translate', function(Translations, Language) {

  function translateFilter(input) {
    return Translations[Language.getCurrentLanguage()][input] || '';
  };

  // Marking as stateful
  translateFilter.$stateful = true;

  return translateFilter;

});

For more information on "stateful" filters, refer to the docs: https://docs.angularjs.org/guide/filter

By the way, for translations, consider using angular-translate. You can explore their filter implementation here: https://github.com/angular-translate/angular-translate/blob/master/src/filter/translate.js

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

Issue with setState not being triggered within axios POST request error handling block

I am in the process of setting up an error handler for a React Component called SignupForm.js, which is responsible for handling user registrations. Specifically, I am working on implementing a handler to deal with cases where a user tries to sign up with ...

Pass an array from a script file in JavaScript to index.js within the Express framework

I've encountered a challenge in sending an array (or JSON object) from script.js to index.js, my express server file. I've explored various solutions such as passing the variable through an HTML file and then to another JavaScript file, utilizing ...

Steps for deactivating AMD on four files and sequentially loading them using webpack

I am facing an issue where I need to disable AMD on 4 files and ensure that video.js is loaded before the other 3 files, as they are dependent on it. My attempt to achieve this in webpack.config.js was unsuccessful: const path = require('path') ...

Ways to conceal an element in Angular based on the truth of one of two conditions

Is there a way to hide an element in Angular if a specific condition is true? I attempted using *ngIf="productID == category.Lane || productID == category.Val", but it did not work as expected. <label>ProductID</label> <ng-select ...

Sharing server object in expressJS with another file through module.exports

As I work on my expressJS app, I encountered a situation where I needed to share the server object with another file. To achieve this, I decided to create the server in my app.js file and then expose it to one of my routes. var server = http.createServer( ...

Trigger a unique event using Vanilla JS and then detect it on Vue instances

I am currently in the process of incorporating multiple Vue instances into my website. I have encountered issues preventing me from making the entire website a Vue instance and using components due to potential conflicts and other complications. For examp ...

A proposal for implementing constructor parameter properties in ECMAScript

TypeScript provides a convenient syntax for constructor parameter properties, allowing you to write code like this: constructor(a, public b, private _c) {} This is essentially shorthand for the following code: constructor(a, b, _c) { this.b = b; thi ...

The Static Interface Binding in TypeScript

I have inquired about how to extend the static functionality of existing objects in JavaScript (using TypeScript). In all examples provided here, I am utilizing Object The code below showcases a polyfill definition for ECMAScript's Object.is function ...

Can a href from a "<Link>" component be passed through a Higher Order Component (HOC) into an "<a>" tag?

I am currently facing a situation with the main component where I have the following code: <Link href={'test'}> <PrimaryAnchor>Welcome</PrimaryAnchor> </Link> Within the PrimaryAnchor component, the code looks like ...

Exploring the Differences between Slim Framework's Currying and Dependency Injection

Frameworks like Angular allow for injecting services and controllers into each other, as shown in the code snippet below: App.controller('exampleController', function($scope, ajaxService){ ajaxService.getData().then(function(data) { ...

Showing various information in tab form depending on a specified variable

In my current project, I am developing a user-friendly view that allows users to easily switch between different sets of data. The specific scenario involves a manager overseeing multiple stores with various franchises. Our dashboard presents aggregated re ...

Transform a span into a div while retaining its content and styles, ensuring compatibility with Internet Explorer

Is there a reliable JavaScript method to convert a span into a div while preserving its contents and the original classes of the span? The classes are pre-set, so hardcoding should be possible. <span class="my class"> <p class="conten ...

Ending JavaScript promises

I am currently utilizing the Google JS closure library which can be found at https://developers.google.com/closure/library/ Below is the code snippet that I have: if (endDate >= wap.com.ifx.util.IfxComponentUtil.yyyymmdd(currentDate) && goog.o ...

Attempting to extract the desired aggregations from a two-dimensional JSON array

Looking to parse through this JSON 2D array (snapshot data example below) to calculate the total cases and deaths for each date, disregarding the state column. While achievable in SQL, it poses a challenge in JavaScript. Ultimately, the summarized data wi ...

What could be causing my Vue application to not launch after executing `npm run serve`?

These past 24 hours have been a struggle for me. I recently embarked on the journey of learning Javascript, and my choice of JS framework was Vue JS. However, when I run npm run serve, my Vue JS app bombards me with numerous errors that seem to make no se ...

Is it possible for a user to modify the JavaScript code on a website?

As I develop a website that heavily relies on JavaScript, I am curious about the possibility of users being able to edit the JS code themselves. For instance, if I have an ajax function that calls a.php, could a user modify the function using Firebug or a ...

Is it possible to execute functions inline with conditional logic in react?

Is there a way to shorten the long conditions inside an inline if-else statement in React by putting a function inside it? I attempted to do this but encountered an error stating that "discount is not defined." function getDiscount(props) { const d ...

Identifying a failed Ajax Request in JavaScript

How can I check if an Ajax request failed to load a file? Here is the code I'm currently using: var pro = undefined; var xmlhttp; if (window.XMLHttpRequest){ xmlhttp = new XMLHttpRequest(); } else{ xmlhttp=new ActiveXObject("Microsoft.XMLHTT ...

Tips for eliminating the glowing effect when pressing down on the thumb of the material ui slider

Visit Material-UI documentation for Slider component. Despite setting the disabled flag for the entire slider, the thumb continues to show a halo effect when clicked. ...

Resetting suggestions for autocompletion in AngularJS

Currently implementing angularJS with autocomplete-alt. The functionality is working smoothly, but I've encountered an issue when clearing the autocomplete input using an AngularJS function - the suggestion list does not update accordingly. How can I ...