Angular gaining mastery over the Form

Here's a snippet of code for a form I'm working on:

<form name="registerForm" novalidate role="form">
    <div class="row">
        <div class="small-3 columns"><label for="pwd" class="right inline">Password:</label></div>
        <div class="small-9 columns">
            <label class="" ng-class="{'error': registerForm.pwd.$error.required && registerForm.pwd.$dirty}"><input type="password" id="pwd" name="pwd" ng-model="registerDetails.password" ng-required="true" /></label>
            <small class="error" ng-show="registerForm.pwd.$error.required && registerForm.pwd.$dirty">Password Required</small>
        </div>
    </div>
</form>

In the code above, you'll notice the registerForm.pwd variable, which combines the form name with the input name. Angular has added properties like $error and $dirty to this variable.

I'm wondering if there's a way for me to add my own properties to it, like registerForm.pwd.$notEqual, perhaps through a directive?

Answer №1

Indeed, please refer to the working demo displayed below.

var app = angular.module('app', []);
app.directive('validPasswordC', function() {
  return {
    require: 'ngModel',
    scope: {

      reference: '=validPasswordC'

    },
    link: function(scope, elm, attrs, ctrl) {
      ctrl.$parsers.unshift(function(viewValue, $scope) {
        if (viewValue === "") {
          ctrl.$setValidity('_required', false)
        } else {
          ctrl.$setValidity('_required', true)
        }

        var noMatch = viewValue != scope.reference
        ctrl.$setValidity('notEqual', !noMatch)
      });

      scope.$watch("reference", function(value) {
        ctrl.$setValidity('notEqual', value === ctrl.$viewValue);

      });
    }
  }
});
app.controller('homeCtrl', function($scope) {

});
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<div class="container" ng-app="app">
  <form name="registerForm" novalidate role="form">
    <div class="row">
      <div class="small-3 columns">
        <label for="pwd" class="right inline">Password:</label>
      </div>
      <div class="small-9 columns">
        <label class="" ng-class="{'error': registerForm.pwd.$error.required && registerForm.pwd.$dirty}">
          <input type="password" id="pwd" name="pwd" ng-model="registerDetails.password" placeholder=" password" ng-required="true" />

        </label>
        <label for="pwd" class="right inline">Confirm Password:</label>
        <input type="password" id="password_c" name="pwdConfirm" ng-model="registerDetails.passwordConfirm" placeholder="confirm password" valid-password-c="registerDetails.password" ng-required="true" />

        <p class="error" ng-show="registerForm.pwd.$error.required && registerForm.pwd.$dirty">
          Password Required
        </p>
        <p ng-show="registerForm.pwdConfirm.$error.notEqual" class="error">
          Passwords do not match.
        </p>

        <p class="error" ng-show="registerForm.pwdConfirm.$error.required && registerForm.pwdConfirm.$dirty || registerForm.pwdConfirm.$error._required ">
          Confirmation Required
        </p>
      </div>
    </div>

  </form>
</div>

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

What is the method for accessing a selector within a foreach loop?

Whenever a user clicks on a date in the jquery datepicker, two ajax calls are triggered. The goal is for the second ajax call to populate the response/data into a paragraph with the class spots within the first ajax call, displaying available spots for th ...

Is it necessary to establish a connection to my mongodb database directly within my jest test file, or is it permissible to invoke functions from separate classes that handle the database connection?

Currently in the process of testing my database functions using jest. My javascript file contains a variety of functions that connect to the database, retrieve data, and return an array. The issue I'm facing is when calling these functions from my jes ...

Executing the onSuccess callback in Ajax without any ability to manipulate the ajax requests

My dilemma lies in needing to execute a JavaScript function upon the successful completion of an AJAX call. Unfortunately, I am unable to directly manage the AJAX calls as they are handled by the DNN5 framework. Is there a way for me to trigger my functio ...

Guide to selecting text within an unordered list on an HTML webpage without a distinctive identifier with Python Selenium

I am looking to automate the selection and clicking of the text 'Click Me Please' within a hyperlink using Python Selenium. The main challenge is that there is no distinct identifier for this item as it is nested within a list. The specific HTM ...

EJS dilemma - struggling to incorporate external views

Struggling to include external files in EJS is a common challenge. My project structure is quite straightforward: /lib/ejs-template.ejs /views/home.ejs /views/header.ejs In home.ejs, including header.ejs should be easy, following the documentation: . I ...

Every single data attribute is unique for each element

Hello! I'm currently working on creating a sorting system for pictures, documents, and videos. Each div contains data-extension attributes, so my plan is to filter out all attributes that are jpg, gif, or png and make them visible while hiding the oth ...

Learn how to create a half and half color scheme in an HTML table

I have created an HTML table that resembles a calendar. Various events are registered in the calendar, each distinguished by its color. However, I am looking to change the colors of the cells to be half and half. https://i.sstatic.net/gaQq2.png The imag ...

MongooseError: The operation `users.findOne()` has encountered an issue

While working on my movie website, I encountered an issue when setting up the login feature. When trying to register using POST through Insomnia, I received an error message stating "MongooseError: Operation users.findOne() buffering timed out after 10000m ...

Choose from a range of knockout fetching options for the select feature and choose one

Upon loading my page, there is a <select> element positioned. I am utilizing knockout data-bind to retrieve the values like this: <select data-bind="attr: { id: 'input-' + id(), required: !allowBlank }, option ...

Is it possible to generate distance between 2 elements without utilizing padding or margin?

In my React Native project, I'm currently working with 2 inline buttons - the search and add buttons: https://i.stack.imgur.com/tKZrf.png I'm looking to add some spacing between these buttons without impacting their alignment with the left and ...

Updating certain fields in AngularJS with fresh data

I am facing a challenge with the following code snippet: <div ng-controller="postsController"> <div id = "post_id_{{post.postid}}" class = "post" ng-repeat="post in posts"> ...... <div class="comments"> < ...

How can Protractor be used to test content before Angular is fully loaded?

In my opinion, it's crucial to notify users when an Angular-based application is loading. For instance, in the case of Angular 2, you could use something like <view>Loading...</view>. I'm confident that there must be a similar method ...

What is the reason behind the image not displaying before the AJAX request is initiated and then disappearing once the request is completed?

I am attempting to display a "loading" gif while my AJAX request is being processed. Below are the functions I am using: beforeSend: function () { $('.form-sending-gif').show(); console.log("The beforeSend function was called"); } and ...

Converting the Python/Flask Backend into a Vue.js Frontend Interface

Recently, I delved into the world of frontend to backend communications. To learn more about this concept, I decided to create a small backend program using the boto3 module in Python to fetch data. The backend program I created is functioning perfectly w ...

I'm having trouble locating my route for some unknown reason

I've set up a basic code structure to test my routes, but I keep getting a 404 error. Although I have an app.all function to catch errors, I'm having trouble pinpointing where the issue lies. Below is my index.js file, where I've configured ...

The MUI Slide Transition experiences a malfunction when using multiple Slide components simultaneously

I'm having trouble getting the animations to work for each mui Slide when the button is clicked. It seems like they don't want to cooperate and work together. Oddly enough, if you disable one of the slides, the other one starts working fine, but ...

The position of a jQuery element gets reset when both the show and stop animations are used

When I use jQuery's .position() to place an element, everything works fine. But as soon as I display an animation and then cancel it with an ajax call, the position of the element resets. function displayMessage(msg) { var $messageEl = $('#u ...

Exploring JSON Data with the Wikipedia API

My current project involves extracting text from Wikipedia articles using their API, which is not the most user-friendly tool. I am facing challenges with parsing the JSON object that I receive in return. The key containing the desired text is labeled &apo ...

Headers cannot be set once they have already been sent in NodeJS

Here is the code where I authenticate users in a group, push accounts into an array, and save them using a POST request on /addaccount. groupRouter.post('/addaccount', Verify.verifyOrdinaryUser, function(req, res, next) { Groups.findById(req.bod ...

The storage of HTML5 data is not being saved locally

<html> <head> <title></title> <style type="text/css"> body { font-family: tahoma; } h2 { font-weight: bold; border-bottom: 2px solid gray; margin-bottom: 10px; } #dat ...