Tzof Tzof - 9 months ago 24
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

addClass()
?

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.

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


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) {
  $scope.val={};
});
.has-error{
 border-color:red;
}
<!DOCTYPE html>
<html ng-app="plunker">

<head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-require="angular.js@1.5.x" data-semver="1.5.11"></script>
</head>

<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>
            </p>
        </div>
        <button>Submit</button>
    </form>
</body>

</html>

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