Angular oppositional $watch

Can an inverse use of $watch in Angular be implemented?

The Issue

I am using angular-translate and I aim to execute a $http.put for every missing translation. However, I encounter the following error:

"10 $digest() iterations reached" when trying to $http.post() from ng-translate error handler

Possible Solution

To address this, I have initialized an array to hold all IDs of missing translations. Once the page is loaded, my plan is to send this array to the backend, where the IDs will be validated and stored in the database.

The Query

How can I determine when the page is fully loaded, or in other words, how do I ascertain when Angular is prepared to add the missing translations to the array? I am considering using an inverse $watch function that triggers when there are no elements in the array/collection for a specified duration, like 1 second. Is this feasible, or are there better approaches to tackle this issue?

I cannot provide any specific code examples as the functions utilized are basic such as $http and array.push.

Answer №1

When trying to determine if the controller has finished fetching and binding data to the template, there are various solutions that can be implemented. The approach to take would depend on whether the translation id strings are obtained from an endpoint or already exist in the template. Here are a few suggestions:

  • This response demonstrates the use of directives within the template.
  • Another solution involves checking for $viewContentLoaded.
  • Alternatively, you could utilize $timeout without specifying a specific duration.

Answer №2

When making an $http call, you can utilize promise callbacks such as then(), catch(), finally() to handle the response accordingly:

$http.put('api/someEndpoint').then(function(response) {
    // $scope.someArray.push(response.data);
    // this.someArray.push(response.data);
});

If your translations or items are within an ng-repeat loop, you can refer to this solution for executing a function after ng-repeat finishes and triggering events using $emit along with listening using $on on either $scope or $rootScope.

app.controller('SomeController', function SomeController($scope) {
    // executed when ng-repeat reaches its last iteration
    $scope.foo = function() { $scope.$emit('someEvent') });

    $scope.$on('someEvent', function() { // event triggered, perform actions like $http });
});

The method of populating items with IDs may not be entirely clear, but that is one possible approach.

I hope that explanation proves useful!

Answer №3

After browsing through a related StackOverflow question, I put together a small demo inspired by it. You can check out the demo here.

In this setup, there's no need to worry about whether the page is ready or not. We integrate our process with the useMissingTranslationHandler of the translate service. Below are snippets of code from the demo plunk attached:

angular
  .module('app', ['pascalprecht.translate', 'ngCookies'])
  .service('customTranslationHandlerService', ['$http', function ($http) {

    this._queue = {};

    /* queue items to push to server ....*/
    this.pushToQueue = function (missingTranslationId) {
      if (!this._get(missingTranslationId)) {
        this._set(missingTranslationId);
      }
      this._start();
    }
  }])
  .factory('customTranslateMissingTranslationHandlerLog', ['customTranslationHandlerService', function (customTranslationHandlerService) {

    return function (translationId) {
      customTranslationHandlerService.pushToQueue(translationId);
    };
  }])
  .config(['$translateProvider', function ($translateProvider) {

    $translateProvider.useMissingTranslationHandler('customTranslateMissingTranslationHandlerLog');
  }])

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

Tips for saving/downloading generated QR codes in React Native

Using this code allows me to generate QR Codes, but I am struggling with saving the generated QR Code in PNG or JPEG format. I have tried a few examples without success and I am continuing to try different methods. import React, { Component } from 'r ...

When the user clicks, I plan to switch the audio source

I am looking to update the audio source when a button is clicked, but I am having trouble getting it to work. image description data() { return { audioSrc: '' } }, methods: { setActiveAudio(item) { this.$refs.audioE ...

assigning attributes to web addresses

Is there a way to set a style property for webpages by targeting addresses that contain /index.php/projecten/ instead of specifying each complete address in the code? Currently, I am using the following code: <ul class="subnavlist" style="display: &l ...

Utilize Bootstrap button dropdown to automatically assign a selected value to a list item

I have a form with a select box that transforms into a bootstrap button after the page loads. However, I am unable to set the selected value for the converted bootstrap button drop-down li. <button type="button" class="btn dropdown-toggle btn-default" ...

Is it possible for a PHP form to generate new values based on user input after being submitted?

After a user fills out and submits a form, their inputs are sent over using POST to a specified .php page. The question arises: can buttons or radio checks on the same page perform different operations on those inputs depending on which one is clicked? It ...

Obtaining the scene's coordinates in Three.js

Struggling with a coding issue, I've scanned various discussions that don't quite address my specific problem. Any assistance would be greatly appreciated. In my HTML document, I am using the three.js library to create a scene titled scaledScene ...

A recursive approach to filling empty space on a canvas using Javascript

My goal was to develop a recursive function that would continue filling the empty spaces of a canvas until reaching the edges or encountering a different colored space. function createFillingPoint() { let x = points[0][0], y = points[0][1]; var pat ...

After a loop, a TypeScript promise will be returned

I am facing a challenge in returning after all calls to an external service are completed. My current code processes through the for loop too quickly and returns prematurely. Using 'promise.all' is not an option here since I require values obtain ...

Issue encountered during testing does not appear in final compilation and prevents tests from executing

Embarking on my maiden voyage with Angular 5... Currently in the process of setting up a Jasmine test tutorial found at this link: https://angular.io/guide/testing. However, upon initiation, an error throws me off course: ERROR in src/app/pizzaplace.serv ...

The hide() and on() methods are not compatible with Internet Explorer (IE)

My code is working fine on Google Chrome, but for some reason it's not functioning properly on Internet Explorer (IE). I'm using IE11 and really need this to work on all browsers. Please help me figure out what's going wrong here. $(' ...

Difficulty with collapsing and expanding levels in Bootstrap 4 sidebar navigation

Having some trouble with my vertical Nav created using bootstrap 4. I have 2 levels of lists, but when I click on one dropdown, the other dropdown doesn't close. Here is a link to the issue: https://jsfiddle.net/thilanka/cr0Lfmd1 <ul class="na ...

Why does JavaScript function flawlessly in FireFox, yet fails completely in other web browsers?

When it comes to browsing, FireFox is my go-to browser, especially for testing out my website Avoru. However, I recently encountered an issue when checking the functionality of my code on other major browsers like Google Chrome, Opera, and Safari. It seems ...

Leveraging Django variables in JavaScript

Within my collection of lops models lies a catalog of programs that serve various purposes. I am aiming to utilize the name attribute as a parameter for a javascript function. I have made alterations to some of the lops, appending "ver2" at the end of the ...

My collection consists of objects arranged in this manner

let attributeSet = [{ "id": 1, "value": 11 }, { "id" : 1, "value": 12 }, { "id" : 1, "value" : 13 }, { "id": "2", "value& ...

Struggling to prevent keyboard-triggered date changes in the MUI DatePicker API

Link to CodePen: codepen.io/s/jk3sgj?file=/demo.tsx Is there a way to prevent users from manually typing in dates and force them to select a date from a modal picker instead? I tried using the ReadOnly prop, but it disabled the entire input field, includ ...

Creating a worldwide object in JavaScript

I am trying to create a global object in JavaScript. Below is an example code snippet: function main() { window.example { sky: "clear", money: "green", dollars: 3000 } } However, I am unable to access the object outside th ...

Looking for assistance in setting a new initial state for a javascript toggle on page load

Need assistance with customizing the Youtube-TV JS plugin for a client website? The current setup loads the player with a playlist in an open state, but the requirement is to load it with the toggle closed, displaying the array of playlists instead. If y ...

A more efficient method for changing all corresponding properties located at varying depths within a nested object

When working with JSON data from an API, I often need to parse and modify specific property values. The challenge arises when the nesting structure of the JSON data is inconsistent and beyond my control. For example, I cannot always rely on a fixed depth ...

Create custom dynamic asset tags in AngularJS inspired by Mixture.io's features for seamless HTML templating

Curious about the potential for creating dynamic asset tags within Angular and, if so, the method to achieve this. Here's the backstory: I've been utilizing Mixture.io for templating and have become accustomed to its seamless and adaptable natur ...

Divide the string into two equal sections with nearly identical lengths

Given a string: "This is a sample string", the task at hand is to split it into 2 strings without breaking any words. The goal is to create two strings with the closest length possible, resulting in: ["This is a", "sample string"]. For example: "Gorge i ...