Experiencing an issue where AngularJS $watch function is executing twice, making it difficult to compare old and new values for a

I'm working with AngularJS and I'm trying to monitor a variable for changes in order to decrease another variable. This is the code snippet I have so far:

$scope.$watch('watchMe', function () {
    $scope.decreaseMe--;
)

The watchMe variable is accessible across all scopes. I am using only one controller which handles both the function that modifies watchMe and the watch itself.

Each time watchMe changes, the watch function runs twice due to how Angular functions. However, this causes decreaseMe to be decremented twice as well, leading to an incorrect value.

I've attempted to compare old and new values but haven't been successful in resolving the issue.

When watchMe changes once, these are the values I observe for old/new/decreased:

old: 7  new: 8 
decreasing  5
old: 7  new: 8 
decreasing  4 

How can I adjust my code to ensure decreaseMe is decreased only once when watchMe changes?


Update:

I tried creating a Plunkr example to demonstrate this problem but the $watch function in Plunkr only triggers once.

Answer №1

Is this function not operational?

$scope.$watch('watchMe', function( updatedVal, pastVal ) {
    if( updatedVal != pastVal ) {
        $scope.decreaseMe--;
    }
});

Answer №2

To get a better understanding of your setup, it would be helpful if you could provide more code samples. From my experience, I encountered a similar issue in the past when I accidentally included the AngularJS library twice on the same page.

Answer №3

Encountering a similar issue arose for me while utilizing directive templates alongside a shared controller. This resulted in the controller code executing twice.

(To confirm this, try logging to the console outside of your watch statement - you'll likely observe a duplicate entry)

.directive('directiveOne', function () {
    return {
        templateUrl: 'app/templates/directive-one.html',
        restrict: 'A',
        controller: 'directiveController'
    };
})
.directive('directiveTwo', function() {
    return {
        templateUrl: 'app/templates/directive-two.html',
        restrict: 'A',
        controller: 'directiveController'
    };
})

The resolution I found was to segregate them into their individual controllers

For instance:

.directive('directiveOne', function () {
    return {
        templateUrl: 'app/templates/directive-one.html',
        restrict: 'A',
        controller: 'directiveOneController'
    };
})
.directive('directiveTwo', function() {
    return {
        templateUrl: 'app/templates/directive-two.html',
        restrict: 'A',
        controller: 'directiveTwoController'
    };
})

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

When initializing a local scope property as null in Angular.js, it may end up being undefined

Recently, I created a custom Angular directive. <location zipcode="35423" cityname="" statecode=""></location> Within the directive, I defined the following: scope: { zipcode: "@", cityname: "@", ...

Using a jQuery gallery can cause links to become unresponsive and unclickable

While creating a responsive webpage with the Zurb Foundation framework, I encountered an issue when trying to incorporate nanoGallery which also uses jQuery. After adding the gallery scripts, the top menu generated by the Foundation script became unclickab ...

Using VueJs to create custom Like and Unlike buttons with Vfor loop

How can I make the buttons increase separately? I've tried similar solutions, but they currently increase the number of likes and dislikes together at the same time. Additionally, I am receiving this message in the console: vue@next:1250 [Vue warn]: ...

I aim to trigger a Redux action utilizing react-router-dom

In light of a route adjustment, I am in search of an improved method for invoking the redux action. One option is to invoke a redux action through the render function, as shown below: render(){ const filterName = this.props.match.params.product this.p ...

Decoding JSON in Angular

Hey there, I'm facing a bit of a challenge. My Angular JSON GET process is grabbing the results properly, but I'm struggling to parse and access individual values from the result. Here's the string result that I receive: {"result":[{"sys_i ...

"Error encountered in @mui/x-data-grid's ValueGetter function due to undefined parameters being passed

I'm currently using @mui/x-data-grid version 7.3.0 and I've encountered a problem with the valueGetter function in my columns definition. The params object that should be received by the valueGetter function is showing up as undefined. Below is ...

List with sortable buttons using jQuery UI

After reviewing the demonstrations and explanations provided in the jQuery UI example and guide, I have implemented the following HTML code: <ul class="sort"> <li> <button>A</button> </li> <li> <button& ...

Configuration and debugging of UI Router

I'm implementing ncy-angular-breadcrumb with UI routes. I have a module dedicated to hosting the UI routes: (function () { var app = angular.module('configurator.uiroutes', ['ui.router', 'ncy-angular-breadcrumb']); ...

Organization of a Project using Silex and Angular JS 2

After successfully creating a small app using Angular 2 and REST APIs, I am now interested in incorporating both the backend and frontend into a single project. I am currently exploring Silex as a potential solution to build an application with Angular 2 ...

Achieving functionality with Twitter Bootstrap's "Tabs" Javascript in a Ruby on Rails application

Encountering a JavaScript issue within a Rails application. Although Twitter's documentation is very clear, I'm still struggling to make dynamic tabs work (tab switching and dropdown). I even went ahead and copied their source code, downloaded t ...

How can you connect templates to actions and models in AngularJS directives?

I am currently working on building a custom directive that has presented me with two challenges. Take a look at the template provided below... restrict: 'A', require: '?ngModel', template: '<div>' + ' ...

AngularJS includes a feature where you can dynamically add elements to the DOM by

My goal is to create a dynamic table where clicking on an element will display details in the next line. Here is my implementation: <table ng-controller="TestCtrl"> <tr ng-repeat-start="word in ['A', 'B', 'C']"&g ...

Choosing the Right Server Software for AngularJS Web Development

I'm seeking clarification on a particular concept: After being away from web development for around 3-4 years, I'm feeling lost as I try to get back into it and catch up with the latest technologies. In the past, I was accustomed to using JSP/P ...

Creating an Ionic popover from a template: How can I dynamically pass parameters in the URL?

Here is the code snippet that I am working with: $ionicPopover.fromTemplateUrl('templates/popover_available_sounds.html', { scope: $scope, }).then(function(popover) { $scope.popover = popover; }); ...

Alert from Google Chrome about Service Worker

My situation involves using FCM for sending web notifications. However, I am encountering a warning and the notifications are not functioning as expected when clicked (i.e., opening the notification URL). Below is my Service-Worker code: importScripts(& ...

Is it possible to add a tooltip to a div without using any JavaScript or JQuery?

I've been working on designing a form that includes tooltips displayed constantly on the right side to assist users in completing their forms. To achieve this, I have separated each part into Divs and added a tooltip for each one. <div title="This ...

How to include a variable in a JSON array?

Currently working on a project in Python and I am looking for a way to make changes to this JSON file This is the original data: { "name": "UVIDOCK", "date": "03/14/2018", "cola": "18:18:00", "colb": "6.70000" } I need it to look like this: window.data ...

Retrieving specific arrays from documents in MongoDB

[ { _id: 555, names:['John','Doe','David'] }, { _id: 625, names:['David','Mark','Carl'] }, { _id: 299, names:['Bill','Carlos','Ventus&apo ...

Preserving color output while executing commands in NodeJS

My Grunt task involves shelling out via node to run "composer install". var done = this.async(); var exec = require('child_process').exec; var composer = exec( 'php bin/composer.phar install', function(error, stdout, stderr) { ...

What is the method for altering the icon within the KeyboardTimePicker component in material-ui-pickers?

Is there a way to customize the icon displayed in the KeyboardTimePicker component? I've looked into KeyboardButtonProps and InputAdornmentProps but I'm still unsure of how they can assist me... Link to my customized KeyboardTimePicker ...