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

Issue with making requests across origins in Vuejs using axios

Currently, I am utilizing Vuejs and axios for handling web requests. So far, I have successfully managed to perform GET, POST, and PUT operations. However, the new challenge that I am facing is uploading media to the server. The server necessitates sending ...

Angular Search Version 2.0

I am facing an issue with my search functionality in Angular 2. When I type into the search box, the search method on the service is not triggered. I believe there might be a simple solution that I am missing. Any assistance would be greatly appreciated. ...

Discovering instructions on locating Material UI component documentation

I'm having trouble locating proper documentation for MUI components. Whenever I attempt to replicate an example from the site, I struggle to customize it to fit my requirements. There are numerous props used in these examples that I can't seem to ...

Exploring the depths of design in material-ui

I've just started diving into material-ui and decided to create a simple app in the SandBox: https://codesandbox.io/s/eager-ride-cmkrc The styling using jss is a bit unusual for me, but with your help on these two exercises, I'm sure I'll ...

Eliminate the registration message from TinyMCE by importing a package

Looking to create a TinyMCE React package, I've been using import { Editor } from '@tinymce/tinymce-react'; However, I'm encountering this message - To remove the message, typically you would add the API key to the .js. in your <scr ...

Elements of Data Pagination in Vuetify Data Tables

My data-table is filled with thousands of data inputs, so I am using the default Vuetify pagination to display only 5, 10, or 25 items at a time on the table. However, I am in need of a way to determine which data is currently visible on the table. For ex ...

Error: Module 'electron-prebuilt' not found

I am encountering an issue with my Electron app that utilizes Nightmare.js after compiling it into an .exe file using electron-packager. Everything functions properly until I click a button that triggers Nightmare.js, at which point I receive the followi ...

Issue when attempting to animate an SVG point using translateX transformation

I am attempting to create a basic animation using the translate X property on a section of my svg when hovering over the element. Here is the code I have so far: <html> <style> .big-dot:hover { transform: translateX(20px); animat ...

What is the reason behind localStorage.getItem consistently returning a string value?

Something strange is happening. In the lib.dom.d.ts file, the type for localstorage.getItem shows as 'string | null', but in my app it always returns a string. Why is this discrepancy occurring? ...

AngularJS ng-model not refreshing

One of the features in my application is a Font Awesome icon picker that allows employees to easily access different icons without having to search for their codes online. However, I am facing an issue where clicking on an icon does not update the ng-mode ...

Add a parameter within a loop using JavaScript

I am currently working on a function with a parameter called menu. removeChildCheck:function(menu){ let removeArrayValues = []; for(var i=0; i < this.checkbox.menu.length; i++){ removeArrayValues.push(this.checkbox.menu[i].value); ...

JavaScript: void(0), Internet Explorer 6, and SWFAddress are all important components

Hello there, We are on the verge of launching a secure website (regrettably, we cannot provide the URL) and have come across a rather obscure bug in IE6 that I am hoping someone may have experienced or could shed some light on. This issue only arises when ...

What is the reason behind negative numbers appearing as "5-" rather than "-5" in the basic calculator coded using HTML and JavaScript?

As I am practicing my coding skills, I encountered an interesting issue. Any operation that results in a negative number displays as wrong, but when using console.logs it shows the correct result. Can someone explain why this is happening? <!DOCTYPE h ...

How do you update the bind value in VueJs when using :value="text"?

My attempts at updating a string when the content is changed inside a textarea are not successful. Vue component: <template> <div> <textarea :value="text" @change="changed = true" @keyup="changed = true"&g ...

What is the process for transferring npm package files to my local project?

Despite my efforts to find the answer, I couldn't locate it and so here I am asking again. What I'm looking for: I need to move a file from node_modules to my project in order to work on it. First attempt: I moved the file I wanted to edit An ...

Which symbol or character corresponds to the public "get symbol" method?

While going through some Typescript code, I came across a line that is giving me trouble to understand. const symbol = Symbol.for('symbolname'); class Something { public get [symbol]() { return true; } ... } I am confused abou ...

Prevent the occurrence of endless looping in serializer (angularjs) by avoiding infinite recursion

Currently, I am working on a RESTful application that involves @OneToMany relationships. The entities in question are Team and Player (where one Team can have many Players, and each Player belongs to only one Team). To prevent infinite recursion, I decid ...

Dynamically filling a second dropdown menu according to the selection made in the first dropdown using AJAX and PHP

Help! I'm feeling a bit overwhelmed. Even though this question has been answered multiple times, I still can't figure it out. There must be something so obvious that I am missing. I want the options in the second select input to be populated dyn ...

"An error of ElementNotVisibleError was encountered even though the element is visible

For the past day, I've been trying to solve this issue. While performing end-to-end testing, I encountered an error when attempting to click on a visible element in the browser: ElementNotVisibleError: element not visible Strangely, the ele ...

Encountered difficulties while attempting to set up React.js

Why am I encountering difficulties installing React? I managed to create a node module file, but it is being automatically deleted. I ran the command npx create-react-app my-app. Below is a screenshot. Aborting installation. npm install --no-audit --save ...