Refresh a module variable or redefine a filter within AngularJS

Can a filter be dependent on a lazy-loaded value?

In my scenario, a language pack is loaded asynchronously and the filter should only reflect the loaded values once they are available.

// setting up the i18n filter
app.filter('i18n', ['localizedTexts', function(localizedTexts) {
  return function(localeKey) {
    console.log(localeKey, localizedTexts) // will show null for the second argument initially

    return localizedTexts && localizedTexts[localeKey];
  };
}]);

// setting up the default value
app.value('localizedTexts', null);

// loading values
app.run(['$http', function($http) {
  $http.get('values.json').success(function(response) {

    // updating the value -- does not invalidate the filter or the view
    app.value('localizedTexts', response);
  });
}]);

I have provided a Plunker demo as well: http://plnkr.co/edit/THTD3UiYgegusCl54Qhp?p=preview

What do you think?

Answer №1

Instead of utilizing a value directly, consider using a factory. Take a look at the associated Plunker

app.factory('localizedTexts', ['$http', function($http) {
  var localizedTexts = {};

  $http.get('values.json').success(function(res) {
    angular.extend(localizedTexts, res);
  })

  return localizedTexts;
}]);

If you find the previous method messy, an alternative approach is to use the $provide Provider and a decorator during the configuration phase to modify the value. Check out this updated PLUNKER

app.value('localizedTexts', null);

app.config(['$provide', function($provide) {
  $provide.decorator('localizedTexts', ['$delegate', '$http', function($delegate, $http) {
    var localizedTexts = {};

    $http.get('values.json').success(function(values) {
      angular.extend(localizedTexts, values);
    })

    return localizedTexts;
  }]);
}]);

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

Validating data with Joi can result in multiple error messages being displayed for a single field

I'm attempting to implement a validation flow using the joi package, which can be found at https://www.npmjs.com/package/joi. 1) First, I want to check if the field category exists. If it doesn't, I should display the error message category requ ...

Implementing change event to activate select dropdown with jQuery

Is there a way to modify the code so that select2 and select3 are disabled by default, but become enabled only when an option is selected in the previous select dropdown (excluding the placeholder "Select your option")? In addition, I want the first place ...

Refreshing the information in the database table

Upon receiving data from the server using ajax, I populate this table: $.each(data, function(i, item) { $('#MyTable tbody').append("<tr>" +"<td>" +data[i].A+ "</td><td>" +data[i].B ...

Capture each touchdown and convert it to currency format

As a novice in the field of JS, I have put in a lot of effort into learning from various sources such as websites, documentation, friends, and other questions on Stack Overflow. However, despite all my efforts, I seem to be stuck at this point. $(docume ...

Floating Action Button is not properly attached to its parent container

When developing my React Js app, I decided to utilize the impressive libraries of Material UI v4. One particular component I customized is a Floating Action Button (FAB). The FAB component, illustrated as the red box in the image below, needs to remain p ...

Adding an array to Vue-Kanban blocks can be accomplished by following these steps

I have a web application where I am integrating the vue-kanban component. My goal is to showcase certain objects from my database on the kanban board, but I could use some guidance on how to incorporate them into the display. Below is the array containing ...

Implementing a Where Condition in JavaScript with the MongoDB whereObj

Working on a project involving JavaScript and MongoDB has led me to a specific collection named test_collection. Within this collection, there is a field/object called test_field_1 which contains test_sub_field_1 and test_sub_field_2. Currently, I am sett ...

Is there a way to direct to a particular section of an external website without relying on an id attribute in the anchor tag?

I am aware that you can link to specific id attributes by using the following code: <a href="http://www.external-website.com/page#some-id">Link</a> However, what if the external HTML document does not have any ids to target? It seems odd tha ...

Is the ng-if directive malfunctioning?

After calling console.log($scope.showAddEvent), it is evident that the variable showAddEvent is being updated. However, the ng-if directive does not seem to reflect these changes as it does not display anything at all. As I am relatively new to angularjs, ...

Refreshing is not necessary when submitting a form using Ajax to post data

Initially, I find myself torn between using method or type, where if I define the method in the form, do I still need to define it in the ajax call? If not, why does ajax return undefined in the console? Furthermore, the code below triggers a 405 POST met ...

AngularJS date and time picker featuring user-defined input validation

Is there an AngularJS component available that offers both a date/time picker and the ability to input dates using the keyboard? ...

Guide to incorporating CSS and JavaScript files in Django using Python

I am currently experiencing issues with loading only static css and Javascript in my Django project. The code I have included is successfully loading image files, but the css and js files are not loading. {% load staticfiles %} <html xmlns="http://ww ...

What is the best way to send information from child components to their parent in React

I'm facing a scenario where I need to increase the parent value based on actions taken in the children components. Parent Component: getInitialState :function(){ return {counter:0} }, render(){ <CallChild value={this.state.counter}/> ...

Create a React application that features a countdown timer using the new Date()

I have attempted to create a countdown timer, but I am encountering a problem with the getTime() function. This function calculates the remaining time by subtracting the current time from the finish time. However, the function is called multiple times ever ...

Issue with AJAX POST method failing to upload the file

I'm having trouble incorporating file upload support into my AJAX post function. Can anyone provide some guidance on what I might be missing? function ajax_post(url, param) { if (url.substr(0, 11) == 'javascript:') { result = &ap ...

Interactive rotating display with constantly updating information

Recently I started learning angularJS and I must say, I am already hooked. I have developed a website that pulls data from JSON files (created by external scripts) locally to show real-time information on various pages. Now, I want to include a sliding car ...

Require an additional button to dynamically load more content and shift all existing elements further down the page

I am looking to implement a "load more" button for an Instagram feed on my website. My current approach involves increasing the height of a specific section while moving the rest of the page down. This is what I have tried: <script> $(document.ready ...

Is it possible to configure a redirect to HTTPS using ng-view for a particular route?

I am currently developing a project using angular 1.5.0-rc0. My configuration involves using angular-route with ng-view, set up as follows: app.config(['$routeProvider','$locationProvider', function($routeProvider,$locationProvider) { ...

Efficiently add an object to the beginning of an array in React/Redux by utilizing the spread

I've been trying to use a redux reducer to add objects to a state array. Everything seems to be working fine, except for one issue. The objects are always added to the end of the array, when I really need them to be placed at the beginning. I've ...

Why does the function yield two distinct outcomes?

I can't figure out why, but when I execute the function (kpis1) by itself, it returns the result (100), however, when I run the function (kpis2) alone, I get the result (97). But when I run both functions together, the results are kpis1=100 and kpis2 ...