Tzof Tzof -3 years ago 102
AngularJS Question

Array of fields from AngularJS

Can I get an array that contains references to the fields in a form (like input, textarea, etc.) and in my code run a function on them, like


To explain what I want to do - after the user submits the form (and invokes the submit() function in the controller) I want to add a red border color on the invalid input.


But this isn't working

Answer Source

You can add a condition on your input like ng-class="{'has-error':yourFormName.$submitted&&yourFormName.yourInputName.$invalid}"

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
<!DOCTYPE html>
<html ng-app="plunker">

    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script src="" data-require="angular.js@1.5.x" data-semver="1.5.11"></script>

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


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download