Issues with updating $setValidity from a directive in AngularJS

My current challenge involves building a custom directive (inspired by an example I came across) to ensure that the confirm password matches the initial password input. Even though all my console.log() statements are executing and displaying, it seems like the validity status is not being updated as expected. The 'pass' value remains true despite seeing "set to false" in the console output.

Here's the code snippet:

<form ng-submit="signup()" name="profileForm">
    <div class="form-group"><label class="form-label" for="input-example-2">Password</label>
        <input class="form-input" ng-model="pnew" type="password" name="pnew" placeholder="Password" required></div>
    <div class="form-group"><label class="form-label" for="input-example-2">Confirm Password</label>
        <input class="form-input" name="confirm" ng-model="confirm" type="password"  placeholder="Password" required pwcheck></div>
            {{profileForm.confrim.$error.pass}}
        <hr>
            {{profileForm.confirm.$error}}
        <hr>
            {{profileForm.confirm.$valid}}
        <span ng-show="profileForm.confirm.$error.pwCheck">the passwords don't match</span>
    <div class="form-group"><button class="btn btn-primary">Sign up</button></div>
</form>

JS code for the pwcheck directive

.directive('pwcheck', function() {   
  return {
    require: 'ngModel',
    link: function(scope, elm, attrs, ctrl) {
      function valid(value){
          scope.$watch("confirm", function(newval, oldval){
            console.log(value);
            console.log(scope.pnew);
              if(value==scope.pnew){
                console.log("success!");
                ctrl.$setValidity('pass', true);
                return value;
              }
              else {
                console.log("set to false");
                ctrl.$setValidity('pass', false);
                return undefined;
              }

          });
      }
      ctrl.$parsers.push(valid);
    }   } });

Answer №1

If you are using your directive on the same element and have ng-model in require, then there is no need to use $watch on confirm. Your code could look like this:

ctrl.$parsers.unshift(validate);
ctrl.$formatters.unshift(validate);

function validate(viewValue){
    console.log(viewValue);
    console.log(scope.pnew);
      if(viewValue==scope.pnew){
        console.log("Success!");
        ctrl.$setValidity('pass', true);
        return viewValue;
      }
      else {
        console.log("Set to false");
        ctrl.$setValidity('pass', false);
        return undefined;
      }
}

For a simple example, check out this plunk: https://plnkr.co/edit/vPbICfSCDnwHKh07DAXJ?p=preview

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

Angularfire2: Access Denied Error When User Logs Out

When utilizing the following method: login() { this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider()) .then(() => { this.router.navigate(['']); }); } An error occurs during logout: zone.js:915 Unca ...

JSON Novice - persistently storing data in JSON during browser refreshes

My AJAX poll was set up following a guide found here: http://www.w3schools.com/php/php_ajax_poll.asp Instead of storing the poll entries from an HTML radio button in an array within a text file as demonstrated in the tutorial, I wanted to save them in a J ...

change the css back to its original state when a key is pressed

Is there a way to retrieve the original CSS of an element that changes on hover without rewriting it all? Below is my code: $(document).keydown(function(e) { if (e.keyCode == 27) { $(NBSmegamenu).css('display', 'none');} ...

Encountering an issue with displaying Firestore timestamps while utilizing onSnapshot() in React Native results in an error

Currently, I'm in the process of developing a chat application using Firestore. The approach involves utilizing Flatlist and querying with onSnapshot() to provide real-time updates for both sender and receiver. Here's an example of my query: con ...

Issue with displaying nested React Elements from Component

I am currently facing an issue with my Collection component, which is utilizing a sub-component called RenderCollectionPieces to display UI elements. Strangely, I am able to see the data for image.name in the console but for some reason, the UI elements ar ...

An instructional HTML/JS dialogue for a linked page

On my website, there is a link that, when clicked, opens a new tab with a page that I don't control. I want to guide the user on what to do next after they are redirected to this new page ("Now please press the green button on this page"). Ideally, I ...

Unable to loop through using ngFor

I have a component that retrieves data from the back-end and groups it accordingly. Below is the code snippet: getRecruitmentAgencyClientPositions(): void { this._recruitmentAgencyClientsService.getRecruitmentAgencyClientPositions(this.recruitmentAge ...

Improper comment placement in Rails with AJAX and JQUERY

I am developing a "comment system without page refreshing" using Jquery and Ajax. Within posts/show.html.erb <%= @post.title %> <%= @post.body %> <%= render 'comment %> posts/_comment.html.erb <%= link_to "Add Comment", new_po ...

Learn how to retrieve the accurate file name and file type using CordovaFile and CordovaFileTransfer

I have a project where I need to dynamically load files from a website. When you click on a link in the browser, it loads the files with the correct names and extensions. How can I implement this functionality in an Ionic app? I am unsure of how to go ab ...

Redirecting an Incorrect Request to a 404 Error Page

I am working on setting up a server that will allow users to access specific valid paths: localhost:9090/admin localhost:9090/project1 If a user enters any other invalid paths, they should be redirected to the root and then to the default path localhos ...

What purpose does the question mark (?) serve after a class name when invoking class methods in TypeScript?

One interesting element within my TypeScript code snippet is the presence of the statement row?.delete();. I'm curious about the significance of the question mark in this context. What would be the outcome if 'row' happened to be null? Ap ...

The process of masking a video with alpha data from another video on canvas seems to be experiencing a

I have a unique setup on my page where I'm masking one video with another. Essentially, when the Play button is pressed, a second video slowly appears over the looping video in the background. This effect is achieved by using a black/white mask transf ...

How to access the isolated scope in a directive's link function with AngularJS

Attempting to work with AngularJS custom directives for the first time. Struggling to grasp the isolated scope within the link function of the directive. Snippet from my app : view.html ... <raw-data id="request-data" title="XML of the request" data ...

Ensure at least one checkbox is selected by using jQuery validation

I wrote the code below to select multiple checkboxes and validate that at least one checkbox is selected. The data submission to the database works if I remove onsubmit="return validate_form()". However, I want to ensure that at least one checkbox is selec ...

Incorporate and interpret a custom JSON object within my Shopify Liquid theme

In an attempt to integrate custom data into my Shopify liquid theme, I stored a JSON file in the assets folder. My goal is to retrieve and parse this JSON object within a jQuery method from a JavaScript file also located in the assets folder. Despite try ...

Static addition of the Button to the parent div is crucial for seamless

Introduction: My current project involves managing interns, and I am focusing on the employee side. Employees have the ability to add, edit, and delete interns through modal popups. Strategy: To avoid unnecessary repetition of code, I decided to create a ...

The form failed to be submitted even after undergoing ajax validation

Although this question has been asked many times before, I am still confused about where I went wrong. My goal is to validate a form using ajax and submit it if everything checks out. Below is the code snippet that I have been working with: ...

I am unable to store a session variable using the GET method

Good day, I am seeking assistance with my code and have been searching for four hours without finding the error. I am working on an exchange where variables are stored in a session. The issue I am facing is that the variable $discount gets cleared every ti ...

How can you adjust the placement of a text geometry?

I have scoured through various resources like stack overflow and google in search of a solution to my problem. I have managed to successfully create a block of text in my scene that reads "Buy Here!". However, I am facing difficulty in offsetting the text ...

send the value of a variable from a child component to its parent

I have created a typeahead component within a form component and I am trying to pass the value of the v-model from the child component to its parent. Specifically, I want to take the query model from the typeahead component and place it in the company mode ...