The AngularJS ngModelController is a powerful tool for managing

How can I accurately check ngModelController validity?

Within my directive, I have a controller object. When I console.log the object from inside the directive, it displays:

console.log(ctrl)

$dirty: false
$invalid: true
$modelValue: ""
$name: undefined
$pristine: true
$valid: false
$viewValue: ""
...

Subsequently, when I use if( ctrl.$valid === true ) to log the object again, it shows the same output as before.

console.log(ctrl); //ctrl.$valid is false
if(ctrl.$valid == true) {
    console.log(ctrl); //ctrl.$valid is false
}

In addition, upon inspecting the element, I notice that the correct ng-invalid class is indeed applied.

I intend to create a plnkr to illustrate this issue, although duplicating it may prove challenging.

Update When I use console.log(ctrl.$valid), it returns true. This clarifies why the condition passes, but not why the object form displays $valid as false.

Furthermore, I have created a plnkr showcasing a similar scenario without encountering the same problem. example

Answer №1

Did you experiment with the following:

console.log(JSON.stringify(ctrl));
if(ctrl.$valid == true) {
    console.log(JSON.stringify(ctrl));
}

or

console.log("$valid is ", ctrl.$valid);
if(ctrl.$valid == true) {
    console.log("$valid should be true and is actually ", ctrl.$valid);
}

This issue could possibly be connected to a previous Chrome bug. It seems like when expanding an object in the console, the value displayed reflects the object state at expansion time rather than log time. Thus, printing the object as a string or cloning it while logging may resolve this.

Update - Providing further insights...

If you execute

var obj = {a: 1, b: {}}; console.log(obj); obj['a'] = 2; console.log(obj);
in the Chrome console, you will observe the following output:

> Object {a: 1, b: Object}
  a: 2
  b: Object
  __proto__: Object

> Object {a: 2, b: Object}
  a: 2
  b: Object
  __proto__: Object

Additional Update

Hoping this clarifies your query. It seems like there might be a situation where you are adding a parser to the $parsers array after calling $setViewValue(...). Consequently, during initial directive initialization, any added validations might not have been executed. To trigger them manually, consider calling something like

ctrl.$setViewValue(ctrl.$viewValue);
after incorporating your parser.

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

How to transform a file into a uInt8Array using Angular

Looking to implement a feature where I can easily upload files from Angular to PostgreSQL using a Golang API. In my Angular component, I need to convert my file into a uInt8Array. I have managed to convert the array, but it seems to be encapsulated in som ...

Does the method in the superclass "not exist" within this type....?

Our TS application utilizes a JavaScript library, for which we crafted a .d.ts file to integrate it with TypeScript. Initially, the file resided in a "typings" directory within the project and everything operated smoothly. Subsequently, we opted to relocat ...

Understanding the source of an useEffect's trigger to create a conditional statement

Within my useEffect, I have two states included in the dependencies array: const [currentTab, setCurrentTab] = useState('open'); const [searchParams, setSearchParams] = useState(''); useEffect(() => { if (condition) { // logi ...

Storing information within a Express application using Postgres

Recently, I've been delving into the world of Express and experimenting with a program that allows users to create events and invite others. While I know about using join tables to retrieve data, I'm curious if there's a way to organize the ...

The Angular User Interface Router is a versatile tool for managing

Managing a large application with over 1500 pages can be challenging. I have opted to use angular UI Router for routing. I am interested in learning about the best practices for handling routing in such a vast application. Should I define all routes in ...

Discover the inner workings of the code below: set a variable called "start" to the current time using the new Date().getTime() method. Create a loop that continuously checks if

I'm having trouble understanding how this code snippet works. Can someone please provide a demonstration? Thanks in advance.... It seems that the code is subtracting 'start' from the current date with new Date, resulting in 0 which is less t ...

When the `back` button is clicked in a browser from a different domain, does it trigger a page reload?

Imagine a scenario where a user accesses mydomain.com. At this point, the history stack contains only one entry. Then, the user clicks on a link within my website that leads to mydomain.com/cool, causing another state to be pushed onto the stack. Now, with ...

Executing an automated process of adding items to the shopping cart using Python without the need to have a

Does anyone know of a way to automate the add-to-cart process using Python without the need for an open browser window? I've experimented with modules like mechanize, but they lack the ability to directly interact with web elements. Currently, I&apo ...

Import HTML document into a Bootstrap Popup

Currently, I am working on creating a modal that loads content dynamically. Below is the JavaScript code I have been using for this task: function track(id,title) { $('#listenTrack').modal('show'); $('#listenTrack').f ...

Error in Continuous Integration for Angular 4: Unable to access property 'x' of an undefined variable

i am trying to display some data on the form but encountering an error: TypeError: Cannot read property 'title' of undefined below is my component code : book:Book; getBook(){ var id = this.route.snapshot.params['id']; ...

Discovering the smallest and largest values in an object literal using JavaScript

I am looking to extract the minimum value from an object literal and utilize it in AngularJS, as shown below: scope.data = { 'studentName' : "Anand", 'socialStudies' : "98", 'english' : "90", 'math' ...

Retrieving the hidden field value using JavaScript on the server side

I'm encountering an issue with asp:hiddenfield where, after changing its value on the client side and trying to retrieve it on the server side, it returns null. Here is my client-side code: function pageLoad() { var gV = $('#<%=Hidden ...

Having trouble sorting data-text values that include colspan cells

Latest Update: Encountered an issue with incorrect sorting and frozen sortings when dealing with a cell containing the colspan attribute. Refer to https://jsfiddle.net/2zhjsn31/12/ where the problem arises for the date 2018-06-24 On https://jsfiddle.n ...

The use of ReactDom.render is no longer permissible in Next.js

I just set up a fresh Next JS application using Next 12. Encountering this issue consistently on every page load in the browser: Alert: The use of ReactDOM.render is no longer supported in React 18. Please switch to createRoot instead. Until you make th ...

Tips for incorporating a download button into a video player using Plyr JS

I'm using Plyr JS and I am trying to add a download option for each video. Here is what I've done so far to make the download option work: Even though I have included: controlsList="nodownload" <video controls crossorigin playsinline contro ...

Dynamically add index to attribute as it updates

Having an issue with my dynamic button element: <button v-on:click="changeRecord(element)" v-b-modal.modal-5>Aendern</button> This button is generated dynamically within a v-for loop. Instead of manually including the attribute name like v-b- ...

Update the variables upon a click event following the completion of an AJAX request

Despite my efforts, I am unable to find a solution to the issue I am currently facing. To address this problem, I have created a script using PHP and jQuery that enables users to promote their "listings" on my website. When users visit a specific page, the ...

The operation of "grunt build" results in a Lexer Error, causing the ng-include

After deploying my unminified code successfully, I proceed to run grunt build and deploy from the dist folder. However, upon checking one of the pages, I encounter a breakage with an error in the console: Error: [$parse:lexerr] Lexer Error: Unexpected nex ...

Tips for modifying and refreshing data in a live table with JQuery

One challenge I'm facing is figuring out how to transfer the data from a dynamic table back into input fields when clicking on the edit button of a specific row. Additionally, I need to update that particular row based on any changes made to the value ...

ngPattern problem

As I work on creating a more user-friendly expiration date input for a credit card checkout form, I encountered a challenge. The goal is to automatically insert a " / " between the expiration month and year as the user types. However, the issue arises when ...