0

I'm trying to add a class to a input tag dynamically depending on a condition, inside a directive. Something like that:

return {
  restrict: 'A',
  require: 'ngModel',
  link: function (scope, element, attrs, model) {
    model.$render = function () {

    if (verify(model.$modelValue)) {
        var elm = getElm(element)

        elm.addClass('default');
      } 
    } 
  }

But if element is an input, then the value is not displayed in the view.

Any guesses about what I'm doing wrong?

1 Answer 1

1

UPDATE

Based on the updated requirements from the comments, we can add async validators to also add the class.

var app = angular.module('myApp', []);

app.controller('MyController', function MyController($scope) {
    $scope.test = "asdf";
  })
  .directive('checkAvailability', function checkAvailabilityFunc($q) {
    return {
      restrict: 'A',
      require: 'ngModel',
      link: function(scope, element, attr, ngModel) {
        ngModel.$asyncValidators.userExist  = function(modelValue, viewValue) {
          var deferred = $q.defer();
          if (modelValue === 'asdf') {
            element.parent().addClass('default');
            deferred.resolve();
          } else {
            element.parent().removeClass('default');
            deferred.reject();
          }
          return deferred.promise;
        }
      }
    }
  });
.default {
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>
<div ng-controller='MyController' ng-app="myApp">
  <div style="padding:10px;display:inline-block;">
    <input type="text" ng-model="test" check-availability>
  </div>
</div>


I am not sure why you have gone to the complex $render for this requirement, please check my below example where we can use ng-class and achieve the same. To know more about ng-class visit here

var app = angular.module('myApp', []);

app.controller('MyController', function MyController($scope) {
  $scope.test = "asdf";
});
.default {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller='MyController' ng-app="myApp">
  <input type="text" ng-model="test" ng-class="{ 'default' : test === 'asdf' }">
</div>

Sign up to request clarification or add additional context in comments.

3 Comments

Hi Naren, thanks for replying. The thing is that I need to add this to 100+ fields depending on a validation. Besides, the class may not be applied to the input element but to one of its parents
thanks a lot! I didn't know about $asyncValidators. Your solution is really ingenious
I had some issues with $asyncValidators so trying $validators went better

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.