Issue encountered during rootScope update

I've encountered an issue with my Angular service that updates the $rootScope. The actual updating process works as intended, but it triggers an error in the console that has me concerned.

app.service("scroll", function($rootScope, $window) {

  this.scrolling = function(delta){
    $rootScope.scroll.current -= delta;
  }

  $rootScope.$apply();

});

Removing the $rootScope.$apply() eliminates the error, but then the rootScope value doesn't seem to update when referenced in my HTML.

For instance, in my HTML:

{{scroll.current}}

Only updates when using $rootScope.$apply(). Is there a more effective method for updating the $rootScope or am I overlooking something?

Error message displayed:

Error: [$rootScope:inprog] http://errors.angularjs.org/1.3.0-rc.5/$rootScope/inprog?p0=%24apply

Answer №1

When you use $rootScope.$apply(), it initiates a $digest cycle in Angular. At any given moment, there can only be one active $digest or $apply operation.

To handle this, you can utilize $timeout.

app.service("scroll", function($rootScope, $window, $timeout) {
    this.scrolling = function(delta) {
        $rootScope.scroll.current -= delta;
    }

    $timeout(function() {
        $rootScope.$apply(); //this will start a $digest cycle
    }, 1);
});

Answer №2

It is possible that your function:

$rootScope.$apply();

gets called unnecessarily at times.

To prevent this, simply include the following line:

if ( !$rootScope.$$phase ) 
        $rootScope.$apply()

$$phase indicates when Angular is processing.

UPDATE: fixed $rootScope.apply() to $rootScope.$apply()

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

Ways to identify an element within a webpage

I'm currently working on creating a chrome extension that can detect the presence of specific elements on a webpage. The goal is to have this extension automatically run every time a new page is opened and display a popup message if the element is fou ...

How can I dynamically assign @ViewChild('anchor_name') to a newly updated anchor element in Angular 2+?

Upon receiving an item through a GET request, I set the item_id upon subscription. In the HTML file, I create a div with an anchor id="{{this.item_id}}". However, I encountered the following error: FeedComponent.html:1 ERROR TypeError: Cannot read propert ...

Creating unique URLs for websites can be accomplished by following these steps:

I am in the process of developing a website where content in the main div within the body section can be replaced. However, I have realized that all content will end up on the same URL. Any suggestions on how to fix this? HTML/PHP(index.php): <htm ...

Having trouble fetching the value of the scope/elm in AngularJS

I am having trouble triggering an event after the user finishes typing in an input field and I am struggling to retrieve the entered value. Below is the code snippet: Javascript var subtitlesApp = angular.module('subtitlesApp', ['ngResour ...

Filtering data in AngularJS by parsing JSON records

I have a JSON file containing restaurant information and I need to display the data by grouping them based on their respective address fields. For example, all restaurants with the address 'Delhi' should be shown first, followed by those from &ap ...

Refreshing Data on Vuetify Range Slider

My goal is to update the value as the slider position changes. [codepen]https://codepen.io/JakeHenshall/pen/WLezNg <div id="app"> <v-app id="inspire"> <v-card flat color="transparent"> <v-subheader>Tick labels</v-subheade ...

Flex items maintaining their size when the window decreases

My goal is to arrange two plotly plots side by side within a CSS flexbox, with the ability to resize them as the window size changes. The issue I'm facing is that while the plots expand correctly when the window is enlarged, they fail to shrink when t ...

Obtaining user roles from server without using JWT tokens

My main objective is to provide user roles from the backend. For instance, if a user wishes to access resources in my backend, they can log in using Google credentials. The Angular app retrieves the access token from the Google authorization server and s ...

Ways to access the value of an attribute in an AngularJS object

Is there a way to access the value of field.jobtype within a controller? var app=angular.module('myapp',['ui.bootstrap','ui.select']); app.controller('mycontroller',function($scope){ $scope.onStateSelected = func ...

Currently, I'm attempting to figure out a way to create a CSS string in my MVC ASP.NET project. Any ideas or suggestions are greatly appreciated

I am currently exploring solutions to generate a CSS string in my ASP.NET MVC Web Application. Specifically, I am interested in creating this at the selector level. For instance, I might have a class named "TableFormat" with the following CSS properties: ...

Failure to display React component on screen

I have developed a React microfrontend application consisting of two sub-apps rendered through the container/ project. Both sub-apps render perfectly in isolation on localhost:8083. However, when attempting to view them via localhost:8080/dashboard, I am p ...

Navigating through a URL to grab a specific JSON object: a step-by-step guide

When I receive a json from a URL containing numerous objects, how can I extract only the slugs provided in the json below? I am open to solutions using either PHP or JavaScript. On one hand, I need to understand how to specifically retrieve the desired ob ...

Promise rejection not handled: Trying to modify headers after they have already been sent to the client

I can't seem to figure out why these errors keep popping up. I've tried looking for solutions online but haven't had any luck. Here is the node function I'm using for an API call: exports.GetEmployeeConfirmationList = function (req, res ...

What is the best way to dynamically add a stylesheet using JavaScript/jQuery?

I've been scouring the web for a solution to a particular issue, but so far I'm coming up empty-handed. We're working with Umbraco CMS for a client's website, and it seems we can't insert conditional comments in the <head> se ...

What is the process for creating a pop-up bubble that appears when the cursor hovers over an image displayed within a table using R Shiny?

I am currently working on code that is almost achieving my desired functionality. I want to make it so that hovering over each question mark in the table will trigger a pop-up bubble displaying the help text, rather than having the text appear at the botto ...

Discovering numbers within a JSON object and extracting them - a step-by-step guide

If I have a JSON object coming from a random dataset and want to search through it to manipulate the number values, how can I achieve this? Looping through the object using for...of allows me to get the keys, but I'm unsure how to access every key-val ...

The variable is currently undefined because it has an array assigned to it

Upon selecting multiple checkboxes for variants, I am retrieving checked data using the following method: get selectedIdsFromViolCategoriesFormArray(): string[] { return this.violCategories .filter((cat, catIdx) => this.violCategoriesFormArr. ...

Alter the value of an input element using JavaScript

There are multiple hidden input fields on the page I'm currently working on: <input a1="2" a2="1" a3="3" name="Value" type="hidden" value="10"> <input a1="4" a2="2" a3="6" name="Value" type="hidden" value="12"> <input a1="6" a2="3" a3 ...

Tips for querying MongoDB schemas that reference other schemas in the field?

Looking to search for a product by its name within the DOC Schema. However, the products are stored as references in another Product Schema with the _id. Below you can find the code snippets to understand the structure: DOC Schema import mongoose from &qu ...

Is it possible to make multiple AJAX requests at the same time using AngularJS

I am looking to simultaneously send multiple AJAX requests. Here is the JS code I have: <a class='btn btn-success' ng-click='getDataajax()'>Re Check</a> app.controller('customersCrtl', function($scope, $http, $ti ...