Monitoring the validity of form inputs using AngularJS's $watch functionality

Why isn't this deep watch triggering as expected?

http://plnkr.co/edit/6FxMS4RlfljBMkprZYQs?p=preview

Could it be that the watch function is not checking Angular attributes starting with $? If so, is there a way to monitor changes in validity beyond just the form and including any input fields?

Answer №1

One effective approach is to monitor .$error, which functions smoothly. Check out http://plnkr.co/edit/6FxMS4RlfljBMkprZYQs?p=preview for more details.

It's similar to observing form's validity, but it updates whenever any of the validations change.

Special thanks to for this insight.

Answer №2

Perhaps at a later time, but I have discovered an alternative method. Utilizing:

$scope.$watchCollection

You can specifically monitor the myForm variable within the scope using $watchCollection and update your buttons or any other elements as needed.

$scope.$watchCollection(function () {
        if ($scope.myForm)
            return $scope.myForm;
    }, function () {
       if ($scope.myForm)
       if (($scope.myForm.$invalid == true))
              $scope.formValidityChange(true);
        else
            $scope.formValidityChange(false);
    }, true);

This will monitor all variables that change within the form and allow you to update the controller. You can also potentially compare the two objects to determine what has changed, although this may be more complex.

Answer №3

The $watch function in AngularJS is used to monitor changes on the $scope object. If the input you are watching is not connected to the same $scope property that is being monitored, the watch listener will only be triggered once during initialization.

To help understand how $watch, data binding, and $scope interact, consider the following representation of your scope (even though it is currently empty due to lack of input):

{
    shizzle: { // <--- The property being watched
        $valid: false,
        whatev: { 
            valid: false
        }
    },
    whatev: "" // <--- The object that changes when you input into the <input>

}

As shown, although 'shizzle' is watched, it remains unchanged, causing the watch listener to execute only once.

Here is an updated version of your plunker that binds the watcher to the input's model and records all changes for illustration:

http://plnkr.co/edit/AbCdEfGhIjKlMnOpQrSt?p=preview

NOTE: To monitor the $valid attribute that Angular is updating, modify the following line:

scope.$watch(attrs.name, function(newVal, oldVal) {
    console.log(newVal);
}, true);

to this:

scope.$watch("shizzle.$valid", function(newVal, oldVal) {
    console.log(newVal);
}, true);

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

Developing middleware for managing event handlers

Scenario: I am tasked with managing multiple events that necessitate an "available client". Therefore, in each event handler, my first step is to attempt to acquire an available client. If no client is available, I will send a "Service unavailable" messag ...

How do I retrieve the HSL value for a color selected using an input of type 'color' in JavaScript?

I am faced with a creativity block and don't know where to begin. My goal is to develop functions that can manipulate the HSL values once I have access to them. Specifically, I am interested in modifying the light value, which is why I require it in ...

Is it possible to incorporate some scripting to enhance the efficiency of deploying my mongoose database?

I'm completely new to setting up servers and diving into back-end development. My technical language is limited, making it challenging to find solutions through online research. I apologize in advance for my lack of expertise in this area. Currently, ...

Troubleshooting a unique CSS bug in jQuery mouseover functionality

Check out this pen: https://codepen.io/anon/pen/eKzEVX?editors=1111 I recently created a Form Select in Laravel: {!! Form::select('status_id', $statuses, $post->status_id, ['class' => 'form-control post-sub-items-label &apo ...

Emphasize the center row within a moving table

I am interested in developing a scrolling table where only 10 rows are visible at any given time, with the middle row set to stand out even during scrolling. The concept is that as the user scrolls down, the highlighted row changes progressively as they c ...

Retrieve the outer-HTML of an element when it is clicked

I am working on a project to develop a tool for locating xpath, and I am seeking the most efficient and user-friendly method for allowing the user to select the desired element on a webpage. Ideally, this selection should be made with just a single click, ...

Filter out empty values in ng-repeat in Angular

I currently have a select element within my code: <select ng-model="applicationStatus" ng-options="p.StatusID as p.Status for p in vm.projects | unique:'StatusID'"> <option value="">All</option> </select> Follow ...

Guide to activating the timer specifically on select pages with jQuery Mobile

I've developed a quiz application using jQuery Mobile and I am working on implementing a timer feature. The timer should run from 0 seconds up to 1 hour but only when the user is viewing specific pages, specifically the question pages. The timer is di ...

Flag is to be set while moving through the input fields

I am currently working on a form with multiple text fields and a text area. I have implemented a loop to go through each of these fields and check if there is a value present. If the field is empty, I set a flag to pass=false. On the other hand, if a value ...

Add a user to a guild using Discord API

Hello, I'm currently working on integrating the Discord API to automatically add users to a guild upon login. However, I keep encountering a 401 Unauthorized error and I'm unsure of the reason behind it. Below is a snippet of my code: const data ...

Unable to integrate npm package into Nuxt.js, encountering issues with [vue-star-rating] plugin

Just starting with nuxt js and running into issues when trying to add npm packages. Below are my attempts. star-raing.js import Vue from 'vue' import StarsRatings from 'vue-star-rating' Vue.use(StarsRatings) nuxt.config.js plugi ...

Are there methods to individually style components that have been generated through the .map() function?

My goal is to style each <Tuner /> component separately, which are being rendered for each item in the this.state.notes array using this.state.notes.map(). I want to position them individually on the page, but currently they all appear together. This ...

Inquiring about monitoring a date object in AngularJS?

Is it possible to monitor a date in angularJS? I have an ng-model that has a date and I would like to monitor it so that I receive a notification when it changes month, year, or day. scope.$watch('ngModel',function(newVal){ console.log(newVa ...

Choosing a dynamic dropdown option using jQuery and AJAX

I am facing an issue with a select box that is dynamically populated and should display information about a single option. The problem I am encountering is that the browser does not trigger a ':selected' event when I click on any of the options. ...

Transform Ajax response into dropdown menu option

I have made an ajax call and received HTML as a response. Now, I need to convert this output into options and add them to select tags on my webpage. <div class="views-element-container"> <div class="view view-contact-view-id-conta ...

What is the best way to specify a submission destination for a custom form component in Vue?

I am looking to streamline the use of a form component across my website, however, I need the submit button to perform different actions depending on which page calls the form-component. Experimenting with Vue components and data passing is new to me as I ...

Tips on eliminating overlapping strokes

I'm having trouble with drawing an array of circles that are meant to intersect a series of lines. The issue I face is that if the circles overlap, a stroke appears underneath them which I want to remove. Does anyone have any suggestions on how to el ...

The Codeigniter ajax call fails to function properly when an external JavaScript file is incorporated

Why does my Codeigniter ajax request work when JS is embedded internally, but not when I try to use it as an external JS file? View the code for the sample_ajax below: <html> <head> <title></title> <scrip ...

The JavaScript codebase is dragging its feet in responding

In my Node and React (NextJS) SSR project, I have integrated the createjs library for JavaScript animations. However, since there is no NPM package available, I had to download the minified JS library and host it locally. After adding this library to the ...

Connect the AngularJS data model with a Foundation checkbox element

I am attempting to link a model (a boolean value) to a checkbox created with Foundation (Zurb). I have created a small demonstration displaying the issue: http://jsfiddle.net/JmZes/53/ One approach could involve simply creating a function that triggers o ...