Validating an Element Directive in AngularJS: A Step-by-Step Guide

I have developed a directive for handling numbers

function numberInputDirective()
 {
    return 
    {
        restrict: 'E',
        scope: 
        {
            model: '=',
            disabled: '=?',
            decimals: '=?',
            form: '=',
            name: '='
        },
        require: '^form',
        replace: true,
        templateUrl: 'directives/pxNumberInput.html',
        link: function (scope, element, attrs, form) 
        {
              scope.inError = function () 
              {
                  return form.control.$valid; //I need to do something like this    
              }
        }
    }

In the isError function, I need to verify if the value in the control is valid or not

The template looks like this:

<input class="input-field form-control" type="number" ng-model="model">

Here is how you would implement it in HTML:

 <form role="form" class="form-horizontal psi-keyrates-yieldform psi-keyrates-historical-topcurves" name="SampleControlsForm" novalidate>
      <px-number-input id="objectiveid" name="numericExample"    model="sampleDataModel.numericField" placeholder="Enter numeric value" label="Numeric" required maxlength="10"></px-number-input>
</form>

While checking if the form is valid can be done through the form variable, we also need to know if this specific directive has a valid value when the form is submitted. Something similar to form.control.$valid.

Since I don't know the name of the control in this directive beforehand, I attempted: var elem = ctrl.$name + '.' + element.attr('name') + '.$valid'; This expression returns "SampleControlsForm.numericExample.$valid", but adding a watch on it does not provide any assistance and neither does scope.$eval.

I am certain that I am not utilizing it correctly.

Answer №1

Below is an illustration of a unique number validation feature that demonstrates:

  1. Guidelines on requiring ngModel to access its controller.
  2. Steps to add a custom validator by appending a property to the $validators object (applicable for angular version 1.3 and above). For versions lower than 1.3, utilize ngModelController.$setValidity
  3. Tutorial on setting up a $watch function on the $error object to dynamically insert/remove an image based on the validation result.
  4. The process of creating a distinct directive compatible with ngModel without defining a specific template.

The $validators object enables the registration of multiple validation directives for the same ngModel. To include a new validator, simply incorporate the validation directive within the same element as ngModel.


var app = angular.module('app', []);
app.directive('myNumber', function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    compile: function(element, attr) {
      var img = angular.element('<img src="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcTTyptDmp09eMq1nHtcJHVTAMkKgqdi1ZiGMQSjFeYNApkO92zhCA" />');
           
      return function(scope, element, attr, ngModelCtrl) {
        function isNumber(n) {
            return !isNaN(parseFloat(n)) && isFinite(n);
        }
        
        ngModelCtrl.$validators.mynumber = function(val) {
          return isNumber(val);
        };
        scope.$watch(function() {
          return ngModelCtrl.$error.mynumber;
        }, 
        function(newVal) {
          if (newVal) {
            element.after(img);
          }
          else {
            img.remove();
          }
        });
      }
    }
  }
});
      
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<div ng-app="app">
  <form name="form">
    <input type="text" name="age" my-number ng-model="age" /> {{ age }}
  </form>
  {{ form.age.$error }}
</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

The importance of understanding Req.Body in NODE.JS POST Requests

Currently, I am developing a Node.JS application that interacts with a MySQL database. The app retrieves data from the database and displays it in a table using app.get, which functions correctly. The issue I am facing is that when utilizing app.post, re ...

Schema Object for Validating Vue Prop Types

React allows you to specify that a prop is an object and define the types of its properties, known as the shape. However, in Vue, it appears that the only method available to determine if an object matches a specific shape is by using the validator funct ...

Summary in Javascript

After utilizing the inspect code tool in PHPStorm, I received the following message: 'recipient_user.id === app.currentUser.id ? true : false' can be simplified to '!!(recipient_user.id === app.currentUser.id)' I'm wondering: ...

html inserting line break using label

I am attempting to dynamically set text to a label using jQuery. However, I am having trouble getting the <br> or \n to create new lines. Instead, all the text displays on the same line and wraps around. If you want to see my code in action, ch ...

apply a visible border to the item that is clicked or selected by utilizing css and vue

I have a list of items that I want to display as image cards with an active blue border when clicked. Only one item can be selected at a time. Below is the code snippet: Template Code <div class="container"> <div v-for="(obj ...

Utilizing AngularJS to show content based on regular expressions using ng-show

With two images available, I need to display one image at a time based on an input regex pattern. Here is the code snippet: <input type="password" ng-model="password" placeholder="Enter Password"/> <img src="../close.png" ng-show="password != [ ...

Vue-router is displaying only the root route

I've been working on vue-router for some time now, but I seem to have hit a roadblock. Despite going through numerous articles and documentation, I can't seem to find the solution. Even after reading multiple tutorials on using vue-router, I&apo ...

`When is it appropriate to utilize dispatch within an action creator function?`

I have created two functions in my ActionCreator.js file. First: export const fetchAudioForVerification = ()=>{ return fetch(baseUrl+'audio',{ // Perform Get Request } .then(response=>response.json());} Second: export const handleAudio ...

Tips for refreshing the direction route in google-maps-react

I have an array of coordinates, and when I add a new coordinate to the array, I want the route direction on the map to update accordingly. This is the code snippet from my googlemap.js file: /* global google */ import React, { Component } from "react ...

The intended functionality of clicking on an image is exclusively reserved for its immediate parent element

I have a feature on my website that displays an image gallery. When a user clicks on an image, it opens up the image in full screen similar to Facebook's theatre mode. I have written code so that when the user clicks anywhere in the container of the i ...

Encountering TypeScript errors with React-Apollo when using GraphQL to pass props to a higher order component

I've encountered some challenges while attempting to link a React class component with my local Apollo cache data. Following the guidelines outlined here, I have run into issues where VSCode and Webpack are generating errors when I try to access data ...

Production environment experiencing issues with Stripe functionality due to element remaining mounted

When making a payment in development mode, everything goes smoothly. However, when I switch to production, I encounter the following error message: v3:1 Uncaught (in promise) IntegrationError: We could not retrieve data from the specified Element. Please e ...

Is the array empty once the functions have been executed?

app.post('/api/edit-profile', regularFunctions, async function (req, res) { let email = req.body.email let password_current = req.body.password_current connection.query('SELECT * FROM accounts WHERE id = ?', req.body.id, asy ...

Issue encountered while creating a token in a JavaScript Chrome extension and attempting to validate it on a backend Node.js server

Trying to create a token within a chrome extension and utilizing it to authenticate requests to the backend server has proven challenging. While successfully generating a token on the front end, encountering an error when verifying it with the google-auth- ...

The combination of Array.pop and Array.indexOf is not functioning as expected

I'm having an issue with using Array.pop(Array.indexOf(value)). It seems to always delete the last element in the index, even if the value of that index is not what I intended. Can someone provide some guidance on how to resolve this? CheckBoxHandle ...

Eliminate web address parameter using regular expressions

Looking to remove a specific URL parameter from a given URL. For instance, if the URL is: http://example.com?foo=bar&baz=boo And I want to eliminate foo=bar to get: http://example.com?baz=boo Or removing baz=boo would leave me with: http://exampl ...

Retrieving the total count of data entries from the JSON server endpoint

Working on a practice application with the JSON server serving as the backend, I have a question. Is there a way to determine the total number of records at an endpoint without actually loading all the records? For example, if my db.json file contains da ...

Angular Controller setup

One common question that often arises is whether placing 'ng-controller' under 'ng-app' in the HTML file negates the need to register the controller in JavaScript. Does it create any issues if the controller is scoped under 'ng-app ...

Error 404 encountered while attempting to delete a MongoDB document using the combination of Express, Mongoose,

Just starting out with the MEAN stack and I have a question. So far, I've grasped the basics of adding data to mongodb using mongoose, express, and ui-router. However, I'm stuck on how to delete a document. Every time I attempt it, I encounter 40 ...

What could be causing my JSON product list to not load properly?

My list is not loading and I can't figure out why. I've included my json, jquery, and HTML below. The console isn't showing any errors, but the list is still blank. Any help would be greatly appreciated as I am new to working with json. Than ...