AngularJS field array

Is it possible to create an array that contains references to the fields in a form (such as input, textarea, etc.) and then run a function on them in my code, like addClass()?

To clarify my objective - I am looking to add a red border color to any invalid inputs after the user submits the form (and triggers the submit() function in the controller).

ng-class="{'has-error':form.input.$invalid}"

Unfortunately, this approach is not yielding the desired results.

Answer №1

If you want to apply a condition to your input, you can use

ng-class="{'has-error':yourFormName.$submitted&&yourFormName.yourInputName.$invalid}"

let myApp = angular.module('example', []);

myApp.controller('MainController', function($scope) {
  $scope.value={};
});
.has-error{
 border-color:red;
}
<!DOCTYPE html>
<html ng-app="example">

<head>
    <meta charset="utf-8" />
    <title>AngularJS Example</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4c2d222b39202d3e62263f0c7d62796234">[email protected]</a>" data-semver="1.5.11"></script>
</head>

<body ng-controller="MainController">
    <form name="myForm" novalidate>
        <div style="padding: 10px">
            <input name="HazardousMaterial" ng-model="value.type" required ng-class="{'has-error':myForm.$submitted&&myForm.HazardousMaterial.$invalid}">
            <p ng-show="myForm.$submitted">
                <span ng-show="myForm.HazardousMaterial.$error.required">Required</span>
            </p>
        </div>
        <button>Submit</button>
    </form>
</body>

</html>

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

Best practice in Angular: Initializing data in a service during start-up

Looking to create an angular service that collects data upon "start-up" and forms an array that remains unchanged throughout the application's lifespan. Avoiding the return of the http request promise is a priority, even though caching the result woul ...

When the cursor is placed over it, a new div is layered on top of an existing

Currently, I am working on a project with thumbnails that animate upon hovering using jQuery. One of the challenges I have encountered is adding a nested div inside the current div being hovered over. This nested div should have a background color with som ...

Even when applying a class, the CSS link:hover style will only affect the initial occurrence

I've hit a wall on this issue and can't seem to find a solution. I styled a few links using classes, but it seems that only the first link is accepting the :hover and :visited state styling. I made sure to use classes to style all of them. Not su ...

Is there a way to determine the orientation of an image in React-Native, whether it is horizontal or vertical

When working with react-native, I aim to utilize the 'contain' feature for vertical images and the 'stretch' feature for horizontal images. What would be the best way to determine the orientation of an image as either horizontal or vert ...

The challenge of page refreshing in IE9 with AngularJS

Everything seems to be running smoothly with my single-page AngularJS application on IE9+ until an object is edited and the page is reloaded. After making a modification (such as changing "You" to "Me" in the Name field) and saving it, the server receives ...

Tips on how to round up numbers in ng-bind

Below is the code that I am working with: <td><span ng-bind="'$' + (o.Price | number : 2)"></span></td> In this scenario, the output value is 68.74. To ensure that this number is more practical, it needs to be ...

What are the disadvantages of not incorporating the main CSS file directly into the web page?

Optimizing the loading time of my webpages is a priority for me, especially when it comes to first-time loading and from cache. Despite that, I still prefer to have the browser re-validate all resources to avoid any strange displays or update issues caused ...

Trigger Ionic's go back function when the hardware back button is clicked within the message app

Currently, I am utilizing the cordova-sms-plugin to integrate the native SMS app within my application. However, I have encountered an unexpected behavior where clicking the hardware back button in the SMS app leads back to my own app and triggers the Io ...

What is the best method for accommodating various web devices effectively?

Those deciding to close this as not conducive, please read through the entire post. Specific questions will be posed at the end. Seeking practical examples and strategies. Situation As more and more people use devices like smart-phones and tablets to acce ...

Issue with jQuery .css() function malfunction in Internet Explorer

While trying to enhance my website, I experimented with the Add class method $("select[name='" + ABC+ i + "']").addClass('addBorder'); To my disappointment, it worked smoothly in Chrome, FF, and Safari but failed in IE. So I decided ...

Combining Tailwind with Color Schemes for Stylish Text and Text Shadow Effects

tl;dr I have a utility class in my tailwind.config.ts for customizing text shadows' dimensions and colors. However, when using Tailwind Merge, I face conflicts between text-shadow-{size/color} and text-{color}. The Issue In CSS, text shadows are oft ...

Styling with CSS in Zend Framework

In the process of creating a website using Zend Framework, I have successfully implemented the header, footer, and all the necessary pages. However, I am facing an issue with integrating the CSS file located at public/css/styles.css. When running the webs ...

<ul><li>issue with indentation

Is there a way to eliminate the indent from my unordered list? While inspecting the element, I noticed what appears to be padding between the width of the box and the content. However, setting padding to 0px and margin to 0px doesn't seem to work as t ...

Loading large amounts of data efficiently with Angular and Firebase

Currently, I am utilizing AngularJS in conjunction with Firebase. Objective: My aim is to showcase all the information stored within my Firebase database (which consists of a fixed number of approximately 1600 items). Challenge: The issue at hand is that ...

Is it possible to dynamically change the color of text based on its position using CSS, JS, or JQuery?

I am currently working on a corporate website and have been tasked with creating a unique design for a specific page. The design includes the following elements: A body background gradient that transitions from their primary color to white in a top-to-bot ...

Converting HTML to a Text String (not for display) using Angular

When it comes to displaying HTML in Angular, there are numerous approaches available. For example, using $sce.trustAsHtml(myHtmlVariable) is one way to achieve this. However, I am interested in creating something like the following: myStringVariable = s ...

What is the best way to reduce the spacing between subplots?

I am working on a subplot with multiple bar charts. Here is the code I have: fig = make_subplots(rows = 4, cols = 1) fig.append_trace(go.Scatter( x=[3, 4, 5], y=[1000, 1100, 1200], ), row=1, col=1) fig.append_trace(go.Scatter( x=[2, 3, 4], ...

"Learn how to showcase a picture in full-screen mode when the webpage is opened

I recently came across a script on Stack Overflow that allows me to select an image at random from an array. The script can be found here: Script to display an image selected at random from an array on page load However, I want to take this concept furthe ...

The behavior of AngularJS checkbox and ng-change is definitely puzzling

I am facing an issue with my array structure: { key : 'abc', color: 'Red', show: true } <div ng-repeat="x in myArray"> <input type="checkbox" ng-model="x" ng-change="changeShow($index)" checked="checked" /> ...

The JavaScript date picker is malfunctioning in the HTML editor, but it functions properly in Fiddle

I have a working format available in a JS fiddle. Here is the code I have used on my demo site: I created a new folder named "js" and placed datepicker.js inside it, then linked it in my HTML like this: <script type="text/javascript" src="js/datepicke ...