The $digest method is refreshing the main $rootScope parent

I'm having trouble grasping the concept of how $digest functions. I came across a response on Angular $scope.$digest vs $scope.$apply that explains it as follows:

" $digest() will update the current scope and any child scopes. $apply() will update every scope. So most of the time $digest() will be what you want and more efficient "

However, in my plnkr example, when I execute

$rootScope.company = "Google";  

and then call $digest() on the second controller, the change is reflected in the parent scope as well. Could this be due to an error on my part?

Plnkr : http://plnkr.co/edit/LTBWTWf7hxlfc5niXsGN?p=preview

Answer №1

Upon reviewing your code, I must say it caught my attention! One suggestion I have is to experiment with the timeout values. For instance, I adjusted the timeout value of the second controller to 1000 ms and discovered that the two 'Google' companies were now the second and third ones.

In addition, I observed that in the third controller, you encapsulate the initialization within an $apply, transforming the code as follows:

app.controller('ThirdCtrl', function($scope, $rootScope) {
 $scope.name = 'Third';

  setTimeout(function() {
      $scope.name = "I'm Third";
     $rootScope.company = "Amazon";
     $scope.$digest();
  },500);
});

This modification effectively resolved the issue for me because the $apply in the third controller was updating $rootScope correctly! :D

However, I would recommend against using $scope instead of $rootScope for this solution. Using $scope may lead to unintended updates and potentially render your final application unstable.

Answer №2

  • $apply :

In charge of triggering the execution of all watchers within the application's scopes by calling $digest on rootScope ($rootScope.$digest()). This essentially initiates a complete life cycle of the application every time $apply() is invoked.

  • $digest :

AngularJS operates in cycles known as $digest, where changes between models and views are evaluated to ensure that the UI and Model are synchronized. The $digest process is responsible for updating the UI accordingly.

It should be noted that invoking $apply triggers $digest on rootScope, causing a reevaluation of all watchers across all scopes. For applications with large scope hierarchies, this may result in a performance impact.

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

JavaScript is experiencing an error where it cannot define a function, rendering it unable to generate a JSON object due to its inability to recognize that the

I've created a JavaScript script function that holds cart items for ordering food. This function takes two parameters: ID and price. Here is a snippet of my script file: <script> function addtocart(mitem, mprice) { var price = ...

Ways to refresh a page after clicking a button inside the modal box

As a beginner in PHP and JavaScript, I am facing an issue with refreshing the page view_create_journals.php when clicking on the change button in the modal. I have added a function to the change button but it doesn't seem to be working. I'm reall ...

The console.log() displays the dictionary correctly, but trying to access it with a key results in it being undefined

I'm currently facing an issue with accessing the dictionary stored in the "workload" field of a document in Firestore. Here is the snippet of code I am struggling with: async addTask() { const projectDoc = await getDoc(doc(db, "projects", "Testing ...

Sending data from local storage to ajax call

Below is the code snippet in question: $.ajax({ url: localStorage.getItem("isntagram link"), // url: "https://api.instagram.com/v1/users/self/feed?access_token=233291163.8a612cd.c49f77de073746e9a2f53116b720302e", met ...

How can we determine in JavaScript when AngularJS has completed compiling its view?

I am having an issue where I need to use a JQ plugin on elements that are defined in an AngularJS View template. Typically, I would call the plugin like this: $(function() { $( "#selectable" ).selectable(); }); However, this approach is not workin ...

A basic structure for a JSON array

Perhaps my next question may appear silly, but I'll ask it anyway :) Here is the structure in question: { "name": "Erjet Malaj", "first_name": "Erjet", "work": [ { "employer": { "id": "110108059015688 ...

Tips for combining values with Reactive Forms

Is there a way to merge two values into a single label using Reactive Forms without utilizing ngModel binding? <label id="identificationCode" name="identificationCode" formControlName="lb ...

Angular grid with a numeric textbox designed for Kendo

I'm attempting to incorporate the Kendo numeric textbox into an Angular application, specifically inside a Kendo grid. I've been unable to successfully bind the data with my Angular object. I've tried adding an "editor" field within the colu ...

Angular - when removing items from ngRepeat, the remaining elements do not transition smoothly; instead, they abruptly snap or jump into position

Currently using AngularJS v1.4.8 with ngAnimate injected into my controller. In the process of creating a dynamic list using ngRepeat, tied to an array. The addition and updating of items in the list function smoothly with animations working as intended. ...

Vue: Simple ways to retrieve state data in MutationAction

I'm having trouble accessing the state inside @MutationAction Here is the setup I am using: Nuxt.js v2.13.3 "vuex-module-decorators": "^0.17.0" import { Module, VuexModule, MutationAction } from 'vuex-module-decorators' ...

Innovative react route

Currently, I am in the process of learning about dynamic react routes. In the code example I am working on, there are different buttons for each task. The goal is to render the WorkDetails component when a button is clicked. However, it seems to not be fun ...

Different approach to iterating through elements

Looking to implement .forEach instead of a traditional for loop? 'use strict'; var score = (function(){ function updateScore() { for(var i = 0; i < arguments.length; i++) { this.score += arguments[i]; ...

Developing Java-based Ajax scripts

Is there a way to implement AJAX functionality in Java without actually using AJAX itself? I'm searching for a JAVA API that can achieve this. Just like we can submit data from a web page using a JAVA program, I want to handle AJAX operations through ...

Tips for sending and accessing multiple parameters in a URL for Node.js/Express GET routes

Currently, I have figured out how to successfully send and access one parameter in my GET router. However, I am unsure of how to send and access multiple parameters in the same way. Below is the code snippet demonstrating how I currently send and retrieve ...

Sporadic success with Ajax operations

The functionality of this ajax code seems to be intermittent. Can someone help me troubleshoot the issue? App.controller('sendemail', function (page) { $.ajax({ type: 'GET', url: 'http://sanjuwebworks.com/conte ...

Issue with toggling options in q-option-group (Vue3/Quasar) when using @update:model-value

I'm a newcomer to the world of Quasar Framework and Vue.js. I recently tried implementing the q-option-group component in my simple application but encountered an issue where the model-value and @update:model-value did not toggle between options as ex ...

Webpack and Keycloak Integration: Content blocked because of MIME type ("text/html")

I am currently using VueJS for my frontend with Keycloak handling authentication, along with Webpack to bundle my code. Upon the initial application load, if the user is not authenticated, they are redirected to the Keycloak page. During this process, an ...

Utilize mapping function to merge arrays

Currently facing an issue with no clear solution in sight. When making API calls via a map, I am able to successfully log all results individually. However, my challenge lies in combining these results into a single array. var alpha = ['a', &apo ...

Flask Server produces a response with a considerable delay when accessed through AJAX

I am currently running 2 servers on localhost, each with different ports. One of them is a basic flask server in Python and its code is provided below: from flask import Flask,jsonify from flask_cors import CORS app = Flask(__name__) CORS(app) @app.rout ...

What are some other options besides object-fit?

Currently seeking a replacement for the css object-fit property that functions properly in Firefox and IE. While it works well in Chrome and Opera, it is not compatible with Firefox and IE. Experimented with the imgLiquid Plugin, but encountered issues w ...