0

Plunker.

TO my textbox I want to apply that errorhilight class when the ng-model contains '' or undefined, and when the submit button click only it need's to check.

<input type="text" class ="errorhilight" ng-model="name"  ng-class="{'errorhilight': (name == '' || name == 'undefined')}">

How can I apply errorhilight class on button click.

Murali
  • 358
  • 5
  • 15

2 Answers2

5

There are many ways you could do it. For example

<input type="text" ng-model="name"  ng-class="{errorhilight: highlightErrors && !name}">
<input type="submit" ng-click="validate();">

$scope.validate = function(){
  $scope.highlightErrors = true
}
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98
0
<input type="text" class ="errorhilight" ng-model="name"  ng-class="{'errorhilight': (name == '' || name == 'undefined')}">

Lets look what you are doing wrong . Here you added the class class ="errorhilight" with and without the condition remove that .

2nd part keep a variable for highlights . Make it true when button is clicked like @Yury Tarabanko solution . But the best way would be to use from validators.

<form id="testForm" name="testForm"   ng-submit="validate()"  novalidate>

    <input type="text" ng-model="name"  name="name" 
       ng-class="{errorhilight: buttonClicked &&  testForm.name.$invalid}"  required >

     <input type="submit" ng-click="validate();">

</form>

and in the controller

$scope.buttonClicked = false;
$scope.validate = function(){
  $scope.buttonClicked = true;
}
Abdullah Al Noman
  • 2,817
  • 4
  • 20
  • 35
  • if you are going to down vote at least leave a comment to say whats wrong .. – Abdullah Al Noman Aug 18 '17 at 09:13
  • I need to validate by checking `{'errorhilight': (name == '' || name == 'undefined')}.` in the html itself – Murali Aug 18 '17 at 09:16
  • required does that for you .. if the value is not there this will do the both .. why would you want to use `(name == '' || name == 'undefined')` when `testForm.name.$invalid` is more cleaner .. using required tag makes it automatically invalid if you dont have any value for the name model – Abdullah Al Noman Aug 18 '17 at 09:19