0

I'm trying to add a class to my element based on whether it's required and empty field. Not sure what I'm doing wrong. My console.log is getting printed but the class is not assigned.

This is my html

<div ng-repeat="supplier in vm.exportSuppliers" class="row">
    <div class="col-xs-5">
        <label ng-show="vm.exportSuppliers[$index].exportSupplier" class="control-label" for="es{{$index}}+Ref">Agreement Reference *</label>
        <label ng-hide="vm.exportSuppliers[$index].exportSupplier" class="control-label" for="es{{$index}}+Ref">Agreement Reference</label>
        <input class="form-control" id="es{{$index}}+Ref" type="text" 
               ng-model="supplier.agreementReference" ng-change="vm.addExportSupplier()" 
               ng-blur="vm.requiredField('es'+$index+'+Ref')" 
               ng-required="vm.exportSuppliers[$index].exportSupplier">
    </div>
</div>

and my function to make sure field is required and not filled in

vm.requiredField = requiredField;

function requiredField (id) {
    if($scope.vm.exportSupplier.form.$error.required) {
        for (var i = 0; i < $scope.vm.exportSupplier.form.$error.required.length; i++) {
            if ($scope.vm.exportSupplier.form.$error.required[i].$$attr.id == id) {
                console.log('invalid required field');
                var myEl = angular.element( document.querySelector( id ) );
                myEl.addClass('top40');
            }
        }
    }
}

What's wrong with my addClass?

LazioTibijczyk
  • 1,701
  • 21
  • 48

3 Answers3

0

Have a look at the below question. I think you could improve your approach by making use of the ternary operators in ng-class.

angular ng-class if-else expression

0

You can add conditional classes by using ng-class and form properties provided by angularjs

You need to add "name" attribute on form and specify novalidate on it

<input class="form-control" id="es{{$index}}+Ref" type="text" 
 name="inputName"
 ng-class="{'error-class': formName.inputName.$invalid && formName.inputName.$touched}"
               ng-model="supplier.agreementReference" ng-change="vm.addExportSupplier()" 
               
               ng-required="vm.exportSuppliers[$index].exportSupplier">

I think this will solve your purpose. No need to write blur function in controller.

0

There are two ways to handle this situation.

Option 1:

    <div ng-class="{'class1': obj.success, 'classB': obj.error}"></div>

Option 2:

    <div class="{{obj.classes}}"></div>

The only problem with this approach is that updating the template could become an issue. Sometimes the controller may not update the template. If that is the case, use $scope.$apply(); after the change has been made.

nitrodmr
  • 198
  • 2
  • 8