Tzof Tzof - 9 months ago 40
CSS Question

Array of feild's form angular

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

addClass()
.

Explain what I want to do: after the user submits the form(and invoke the function
submit()
in the controller), to add red border color on the invalid input.


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


doesn'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