Issue with conflicting trigger events for clicking and watching sequences in input text boxes and checkboxes within an AngularJS application

When creating a watch on Text box and Check box models to call a custom-defined function, I want to avoid calling the function during the initial loading of data. To achieve this, I am using a 'needwatch' flag inside the watch to determine when to call my function. Both the check box and Text boxes are placed inside a span element, so that clicking on the span will set the 'needWatch' flag to true. This ensures that the custom function is only called when that particular model is changed and not during the initial data loading. While this logic works fine for Text boxes and select drop downs, it fails for check boxes.

The issue arises because, for Text boxes, the span's ng-click event always triggers first before the watch function on the Text box model is fired. However, with check boxes, the order in which the watch function and ng-click event are triggered seems to be random. I want the span's ng-click event to always be triggered first for check boxes as well, before its model's watch function. Is this possible?

To see the issue in action and try changing values for both text boxes and check boxes, please visit this plunker.

Answer №1

One aspect that has not been addressed is the ability to input text without clicking on the text field, using the tab key instead.

To address this issue, a better approach would be to utilize ng-change and eliminate the unnecessary use of needWatch. Alternatively, watches can be implemented as shown below:

$scope.$watch('checkboxModel', function(newval, oldval) {
   if (newval != oldval) {
       console.log('watch', newval, oldval);
   }
 }, true); 

Answer №2

When working with Angular, $watch listeners receive both the newValue and oldValue for the watch expression.

To prevent your custom function from running during initialization, you can compare the values of oldValue and newValue. If they are the same, it means the watch was triggered during initialization and your function should be skipped.

The Angular documentation recommends this approach as the standard way to handle the initialization cycle: https://docs.angularjs.org/api/ng/type/$rootScope.Scope

Here is an example:

$scope.model = { textbox: '', checkbox: false };

$scope.$watch( 'model.textbox', function( newValue, oldValue {
    if( newValue === oldValue )
        return;

    customFunction( newValue );
});

$scope.$watch( 'model.checkbox', function( newValue, oldValue ){
    if( newValue === oldValue )
        return;

    customFunction( newValue );
});

function customFunction( value ){
    console.log( "new value: " + value );
}

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

Unable to retrieve or remove cookie sent from Express on client side

My Express server is sending a cookie to the client that is not httpOnly. Despite this, the client is unable to access the cookie through document.cookie or see it in the Application tab on chrome dev tools. Interestingly, I am able to view the cookie in C ...

The outcome of the Javascript Calculator is showing as "Undefined"

I've been attempting to create a calculator using JavaScript, but I'm facing an issue where the 'operate' function keeps returning Undefined, and I can't seem to figure out why. I suspect that the problem lies with the switch state ...

Organize rows in the table while maintaining reactivity

A challenge I'm facing with a web app (Angular SPA) is that it displays a large table without the ability to sort. To work around this issue, I've managed to implement sorting via the console. However, re-inserting the rows after sorting causes t ...

Attempting to retrieve key-value pairs from a nested JSON array

I am attempting to extract values along with their corresponding key names from a nested JSON array resData =[ { _index: 'web', _type: 'event', _id: 'web+0+93', _score: null, _source: { 'os-nam ...

Using Typescript to Import One Namespace into Another Namespace

Is it possible to export a namespace from one typescript .d.ts file and then import that namespace into another .d.ts file where it is utilized inside of a namespace? For instance: namespace_export.d.ts export namespace Foo { interface foo { ...

Retrieving the chosen option from a radio button

<!DOCTYPE html> <html> <body> <input type="radio" name="colors" value="red" id="myRadio">Red color <p>Click the "Try it" button to display the value of the value attribute of the radio button.</p> <button onclick=" ...

Utilizing JavaScript to analyze and interact with a website using Selenium's ghost drivers

Currently, I am attempting to scrape the second page of Google search results using Ghost driver. To achieve this, I am utilizing JavaScript to navigate through the HTML source of the search results page and click on the page numbers at the bottom with G ...

How to customize the button color in a Next.js application

Help Needed: Issue with Changing Default Button Color in Next.JS Web Application. The button text color appears as grey on Desktop Google Chrome, but shows up as blue on Mobile Chrome browser. I want to unify the color to be grey on both platforms. Custo ...

Filter the options in ng-options according to various controls or ng-models

Scenario: In my application, I have a backend built on Laravel 5 and a frontend using AngularJS. The purpose of this application is to allow users to select multiple high-value products that are dependent on each other. A. Initially, the user selects a p ...

Is it possible to verify if each input is unique using the parsley validator?

As a novice, I am struggling with a task where I have 6 School Children IDs. The teacher needs to input these IDs, and while it's not vital for him to enter all of them, he must input at least one. Furthermore, if he decides to input more than one ID, ...

Dealing with unique constraint violation in Mongodb when using insertMany

Currently, I'm in the process of working on a project that involves using node.js and mongodb version 5. In my collection, I have implemented a unique index for the Parcel property. However, during testing, an error is triggered: MongoBulkWriteError: ...

Having trouble figuring out the process of mapping and showcasing data within a React application

On my backend server, I have data displaying in the following format: https://i.stack.imgur.com/f0bfN.jpg I am looking to present this data on my frontend react app. I have attempted the following so far- import {useState, useEffect} from 'react&a ...

Having a minor problem in attempting to retrieve a random value

Having trouble generating a random number from a function. Can someone help explain? const MyButton = document.querySelector(".Flipper"); MyButton.addEventListener("click", recordLog); function recordLog (){ MyButton.style.backgr ...

Click on the checkbox to activate it using JavaScript

I'm trying to use JavaScript to toggle the checkbox status when clicking a button. The first button is supposed to uncheck the box and it's working correctly: function clear() { document.getElementById("check").checked = ""; } However, I al ...

Adding Node Modules during the setup of an ElectronJS application

Hey there! I'm currently working on an ElectronJS application designed for developers. One of the key features is checking for the presence of NodeJS on the user's computer. If it's not detected, the app will automatically download and insta ...

Is it possible to send notifications via email prior to reaching a particular deadline?

I'm trying to figure out a way to notify users one day before dates of events stored in the database. I'm stumped and could really use some help with this. Can someone please assist me? ...

Common mistakes made while working with decorators in Visual Studio Code

Having trouble compiling TypeScript to JavaScript when using decorators. A persistent error message I encounter is: app.ts:11:7 - error TS1219: Experimental support for decorators is a feature that is subject to change in a future release. Set the ' ...

A guide on loading theme JavaScript files in Next.js

I am planning to incorporate a theme from themeforest into Next.js Despite my attempts, I encountered issues with loading jquery core and certain plugins in Nextjs. import { useEffect } from "react" import { SessionProvider } from "next-aut ...

Angular-input-masks offers a unique solution for input masking

I was attempting to create an input mask specifically for CNPJ numbers. After some searching, I came across a solution here. https://github.com/assisrafael/angular-input-masks/ However, I am struggling to successfully implement it. Here is a snippet of ...

unable to choose just one material ui checkbox

I'm new to using React and I'm currently developing a simple todo app with React JS and Material UI. To accomplish this, I've created two separate components - one for taking user input (TodoInput) and another for rendering each individual t ...