Tips for ensuring a watcher only runs once in each digest cycle, regardless of how many times the property is modified

I am facing an issue with my function $scope.render() that relies on the value of $scope.myProperty to render a chart. Whenever myProperty changes during a digest cycle, I need to ensure that $scope.render() is called only once at the end of the digest cycle.

$scope.$watch('myProperty', function(v, vold) {
    if ($scope.switch) {
        $scope.myProperty ++;
        $scope.switch = false;
    }

    $scope.render();
});

The problem here is that if $scope.switch is true, then $scope.render() will be invoked twice within the same digest cycle. How can I make sure it's called only once?

Answer №1

The solution lies in utilizing Angular's convenient $timeout service.

var isChanged = false;
$scope.$watch('myData', function(newValue, oldValue) {
    if ($scope.flag) {
        $scope.myData ++;
        $scope.flag = false;
    }

    isChanged = true;

    $timeout(function() {
        if (isChanged) {
            $scope.updateView();
            isChanged = false;
        }
    });
});

With this implementation, the $scope.updateView function will execute every time there is a change in myData, ensuring it only happens once at the end of the digest cycle regardless of multiple changes to myData.

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

Is it normal for a Firebase listener to trigger twice when adding date to the database in React?

I've developed a basic chat application. Once the user submits a message, it is stored in the database along with their username. this.ref.child("/chat").update({username: this.state.username, message: this.state.chatMessage}); Subsequently, I ...

Enhance your MongoDB with the power of JQuery and ExpressJS combined with the magic

I've successfully implemented a delete function using type: 'DELETE', and now I'm attempting to create an UPDATE function. However, I'm unsure if I'm approaching this correctly. Here's the code I've written so far: ...

Guide on how to showcase an array in a string format using table rows in JavaScript or jQuery

After making an AJAX call to a PHP database, I receive a String as a result in my script. The format of the string is shown below: array(4) { [0]=> array(3) { ["id"]=> string(3) "181" ["number"]=> ...

Automatically generated VueJS function

Creating a logging system for my Javascript Project using VueJS and Vuex To make logging methods accessible to all components, I am utilizing a global Mixin : import { mapState, mapActions } from 'vuex' import LogLevel from '@/enums/logger ...

Troubleshooting a JavaScript Error in AngularJS Module

I created a Module called "app" with some helper functions in the file "scripts/apps.js": angular.module('app', ['ngResource']).run(function($scope){ $scope.UTIL = { setup_pod_variables: function (pods){...} ... }); Now, I want to ...

Using JavaScript to replace a radio button with the term "selected"

I am currently in the process of developing a quiz that is powered by jQuery and possibly JSON, with data being stored in a database. Everything is functioning correctly at this point, but I would like to enhance the user interface by hiding the radio butt ...

Manipulate a property within an array using JavaScript and AngularJS

I am working with an AngularJS model that looks like this: $scope.Model = { Users : [{ UserId: '', FirstName: '', LastName: '' }], Products :[{ ProductId: '', ...

Looking to update table content dynamically using jQuery ajax?

I need assistance in creating a dynamic table that can update its content based on the company selected from a dropdown menu. The data should be fetched using AJAX and only display information related to the chosen company. Furthermore, I would like to imp ...

What exactly is the functionality of the third parameter (usually next()) behind the scenes in ExpressJS once it is hidden behind the abstraction layer?

Consider this scenario: in the following two code snippets, how is the next() function used as a parameter and how does it facilitate the automatic transition to the next middleware function? What is the underlying mechanism that enables this abstraction? ...

Issue with RequireJS: The data-main attribute fails to load the specified file

As I convert my small project into nodejs, I am facing an issue with the requireJS file that defines the JS to be used in the project not loading properly. Below is the structure of my project: https://i.sstatic.net/oYnqn.png The ng-app specifies the fr ...

How can you set the Quill text editor to read-only mode in Vue after clicking a button?

I have a quill text editor that I want to customize the default setting to be readonly. When a button is clicked, this setting should toggle between true and false. Here is my component code: <template> <div ref="editor"></div> ...

Iterating through a jQuery function to increment value

I have encountered an issue while trying to calculate the total value from an array of form fields. The problem lies in how the final value is being calculated on Keyup; it seems that only the last inputted value is being added instead of considering all t ...

Tips for customizing the appearance of a jQuery sortable target list prior to dropping items

When using jquery sortable, I am able to customize a placeholder inside a connected list specified in the connectWith option to visualize where the content will be dropped. However, I am struggling to find a way to style the actual list that contains the p ...

Directing JSON POST Request Data to View/Controller in a Node.js Application

Currently, I am working on a project hosted on a local server at http://localhost:3000/. This server receives a post request from another server in the following manner: return requestLib.post({ url: 'http://localhost:3000/test', timeout ...

What is the best way to add data from an array to a DOM element in the same order it was retrieved from Firebase?

Utilizing Google Firebase Firestore for data storage and the Open Movie Database (OMD) in combination with Axios to retrieve movie information. I am currently developing a website that allows users to add movies to collections. On the collections page, al ...

Updating Rails record using Ajax with select_tag and onchange functionality

I'm working on an index view where I want to update a table data dynamically using select_tag onchange feature without the need to refresh the page. Do I need to use Coffeescript to detect the onchange event, capture the new value, and then send it to ...

How to effectively share an object array between controllers when utilizing modal windows in AngularJS

I'm currently working with an array of objects that I need to share between two controllers, one of which involves a modal window. Check out the JavaScript code below: angular.module('MyApp', ['ngMaterial', 'ngMessages' ...

What's the best way to include various type dependencies in a TypeScript project?

Is there a more efficient way to add types for all dependencies in my project without having to do it manually for each one? Perhaps there is a tool or binary I can use to install all types at once based on the dependencies listed in package.json file. I ...

The color of the button in HTML5 will remain constant and not shift

I have several buttons that function like radio buttons - only one can be selected at a time: <button id="btn-bronze" name="btn-bronze" type="button" class="blue-selected">Bronze</button> <button id="btn-silver" name="btn-silver" type="butt ...

Using jquery to update a link when a different link is clicked

Recently, I've started using JQuery and encountered a challenge. When I click on the first link, an Ajax request is sent to the server and data is received successfully. However, in the callback function, I'm struggling to change the display text ...