I am befuddled by the AngularJS directive that is adding a class

Consider this scenario:

<div class="form-group" ng-class="{'has-error': (form.title.$dirty && form.title.$invalid) }">
   <label for="title" class="col-sm-2 control-label">Title</label>
   <div class="col-sm-10">
      <input ng-model="vm.item.name" type="text" class="form-control" name="title" id="title" placeholder="Title" ng-required="true" />
   </div>
</div>

I have multiple input fields and the

ng-class="{'has-error': (form.title.$dirty && form.title.$invalid) }"
code seems messy to me.

I want to create a directive that simplifies it to just has-error, like so:

<form name="form" has-error=".form-group">
...
</form>

   // Custom directive definition object.
    return {
        restrict: "A",
        require: "form",
        link: function(scope, elements, attributes, form) {
            var selector = attributes["hasError"];
            // 1. Locate all controls with ng-models
            // 2. Validate them
            // 3. Find closest element based on provided selector and add the 'has-error' class
        }
    };
};

.form-group is the selector for the nearest parent container of an input with ng-model.

The question remains: How can steps 1-3 be implemented in an effective AngularJS manner?

Answer №1

Have you considered utilizing the Angular ng-invalid and ng-dirty CSS classes for your input validation needs? These classes are automatically applied to specific inputs with ng-model, and if you require custom validation, refer to the following documentation:

Angular custom validation docs

Here is a straightforward example:

HTML

<form novalidate>
  <input type='text' ng-model='vm.item.name' required>
</form>

CSS

input.ng-invalid {
  border: 1px solid red;
}

input.ng-valid {
  border: 1px solid green;
}

Check out this plnkr demo

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

Is it possible to establish a limit on a field's value in MongoDB?

Just a quick query - I'm curious if there's a feature in mongodb that allows for fields to have a set maximum value. For instance, let's say the field "cards" is restricted to a maximum value of 100. If an increment would exceed this limit, ...

"Clicking on the jQuery carousel dots results in always navigating back to the first item

Creating a carousel using basic jquery, utilizing the .css() rule to toggle opacity between slides. The goal is to have each dot trigger the display of its corresponding slide while hiding the others. Currently trying: $('.dot').click(function( ...

Issue: unable to establish a connection to [localhost:27017]

Upon executing node app.js, an error message is displayed: Failed to load c++ bson extension, using pure JS version Express server listening on port 3000 events.js:85 throw er; // Unhandled 'error' event ^ Error: failed to conn ...

Linking various nodes together using the capabilities of the Web Audio API

I am experimenting with audio and trying to achieve a few specific goals: Adjust the overall volume of the audio. Modify the volume and delay of a particular channel (left). This is the code I have been working on: var audioContext = window.AudioContex ...

Tips for toggling helper messages during form validation using AngularJS

I've integrated ngMessages into my AngularJS application for form validation, and it has been quite helpful. However, I've encountered a challenge that I can't seem to figure out. For example, consider the following code snippet within my F ...

What is the best way to receive a response from the foo.onload = function() function?

My current code involves a function that is triggered by .onload, and I'm looking to return a specific value based on certain conditions: newImg.onload = function() { var height = newImg.height; var width = newImg.width; if(height > wi ...

Methods for automating the clicking of a hyperlink within Bootstrap tabs programmatically

I am attempting to programmatically trigger a click event on a specific href link within Bootstrap tabs. For reference, here is the link to the codepen: linkToCodePen <ul class="nav nav-tabs" id="myNavTabs"> <li class="active">&l ...

Issues encountered with the delete function using distinct row identification format

I am encountering an issue with variable value in input field. To provide some context, I have client information stored in a MySQL database. Using PHP, I retrieve this data and display it in a table. Currently, I am working on implementing a delete optio ...

Exploring through angular.js with the use of identifiers

In my data, I have two JSON objects: all_users "all_users": { "4":{ "user_id":4, "user_name":"Miranda" }, "7":{ "user_id":7, "user_name":"seconduser" } And tickets "tickets": [{ "ticket_id" : 12, "created_by" : ...

What is the best way to retrieve JSON key/value pairs instead of an array?

I am working on retrieving data from a Google Spreadsheet using App Script and have set up a DoGet function. Currently, I am getting an array of data but I need it in JSON key-value pairs format. The table in my Google Sheets is structured as follows: Th ...

Generating HTML table rows dynamically in Angular based on the number of items stored in a $scope variable

In my current project, I am utilizing Angular to dynamically populate data in an HTML table. Instead of manually coding each row for display, I am in need of a solution that allows me to programmatically define each HTML row. The Angular controller snippet ...

When I type text into the form field, JavaScript causes a disruption in the form

I'm attempting to implement a dual-stage user onboarding procedure. Initially, users will input the industry they belong to and then provide a description. Upon clicking submit, my intention is to conceal that portion of the form and reveal the "Creat ...

Why doesn't the element I'm clicking return as expected?

Below is the code provided <!DOCTYPE html> <html> <body> <p id="demo">Demo Element</p> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <script> $('#demo' ...

Determine the quantity of classes based on the part name

I have the code snippet provided below: <ul id="towns"> <li class="clearfix odd 516_499_132_0_0 town132">...</li> </ul> I am looking to extract the specific class "town132" as a parameter, but the number - such as 132 in this ...

Strategies for organizing libraries within mongoDB's system.js

Exploring techniques for storing prototype-based libraries or frameworks in mongoDB's system.js can be challenging. An issue arose when attempting to incorporate dateJS formats in a map-reduce function. JIRA #SERVER-770 clarifies that object closures, ...

Following the completion of every asynchronous operation, a callback will be executed

I am facing a situation where I have an array of images that are uploaded with a series of asynchronous operations as shown below: for ( let key in imageFileObject ) { const imageFile = imageFileObject[key] dispatch('get_signed_request', ima ...

Animating nested ng-repeat loops

Trying to animate a list of elements divided by rows (the parent ng-repeat) and columns (the child ng-repeat) has been quite challenging. While I was able to achieve the desired animation with individual ng-repeats, the same cannot be said for nested ng- ...

Creating a mind map: A step-by-step guide

I'm currently developing an algorithm to create a mind map. The key focus is on organizing the nodes intelligently to prevent any overlap and ensure a visually pleasing layout. Take a look at this snapshot (from MindNode) as an example: Any suggestio ...

Using HTML button to trigger external javascript functions

I am facing an issue while setting up a page to execute an external Javascript function when the user clicks a button in an HTML form. The function named lock() is not being called correctly, and my button code looks like this: <form> <button typ ...

The function 'create' is not a recognized property within the 'Completions' type

Recently, I've been experimenting with ChatGPT and have just installed the latest version 4.8.0. My current project is built on NextJS. Prior to this, I successfully completed a project using v3.something last month, but I'm encountering diffic ...