ng-class not setting class right after conditions are met

841 Views Asked by At

I have an issue where I validate one field using ng-pattern and try to change the look of input using ng-class. The problem occurs when pattern is not met, since at the beginning there is no reaction. My pattern requires that there is at least two characters and no numbers. I know that the ng-class requirement is met because I use the same requirement to trigger the span to show. After I make one more change it triggers(if condition is still met). For example if I typed "a" first, span will show to tell me that this is not ok, but the class will not apply, but if I type "2" next it will trigger. On the other hand if I then change the "2" to "b" ("ab" so pattern is ok) the span will disappear, but the class is still there(until next change of course, ex. adding another letter).

ng-class:

ng-class="{'classValidationError' : orderForm.cc_name.$error.pattern == true}"

HTML:

<form ng-show="itemsCount" name="orderForm" ng-submit="placeOrder()" novalidate>
    <div id="customer-info" class="col-lg-7">
        <div id="customerData" >
        <div class="form-group col-sm-6">
            <label for="cc-name">Imie</label> 
            <input name="cc_name" id="cc-name" type="text" class="form-control" ng-model="customer.firstName" ng-class="{'classValidationError' : orderForm.cc_name.$error.pattern == true}" ng-pattern="namePattern" required ng-model-options="{ debounce: 500 }" ng-change="onChangeValidationWatcher(orderForm.cc_name)">
            <span  ng-show="orderForm.cc_name.$error.pattern" style="color:red;">Wrong format!</span>
            <span  ng-if="orderForm.cc_name.$error.required && orderForm.cc_name.$dirty == true" style="color:red;">This field can't be empty!</span>
        </div>
        </div>
    </div>
</form>

Pattern in controller:

$scope.namePattern = /^[A-Za-z ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]{2,30}$/;

CSS class:

.classValidationError {
    background-color: #FA787E;
}

EDIT:

It seems as if ng-class had some trouble to refresh the classes on the object and does this with a delay. Is there any method like refreshState() or something?

3

There are 3 best solutions below

1
On

replace

ng-class="{'classValidationError' : orderForm.cc_name.$error.pattern == true}"

with

ng-class="{'classValidationError' : orderForm.cc_name.$error.pattern && orderForm.cc_name.$dirty}"

I think it should work properly.

1
On

You can change this ng-class to :

ng-class="{ orderForm.cc_name.$error.pattern == true? 'classValidationError' : ''}"

Using this you can check whether to place that class or not.

3
On

Replace

orderForm.cc_name.$error.pattern 

with

orderForm.cc_name.$invalid

It should work :)