Search code examples
javascriptjqueryangularjsng-class

AngularJS apply class to parent element on event?


I have a form field:

<div class="form-group">
  <label>Name</label>
  <input type="text" name="name" class="form-control" ng-model="abc.user.name" ng-focus="abc.setFocus('name')" required>
</div>

What I need to do is set add a class to the parent element, here <div class="form-group">, when the input has focus and remove it when the field loses focus.

I know how to do this in jQuery, but not in an Angular way. I have many form fields that need to behave like this, so I'm trying to avoid setting a variable and looking for that with an ng-class. I'd rather have some way for the field to simple act on its parent, which I can use the same method in every form field.


Solution

  • A directive is possibly the simplest generic approach if all you need to do is manipulate the dom.

    <div class="form-group" focus-class="focused">
      <label>Name</label>
      <input name="name" class="form-control" ng-model="abc.user.name" required>
    </div>
    

    JS

    angular.module('myApp').directive('focusClass', function(){
        return {
          link:function(scope, elem, attrs){
             elem.find('input').on('focus', function(){
                elem.toggleClass(attrs.focusClass);
             }).on('blur', function(){
                elem.toggleClass(attrs.focusClass);
             });
          }
        }
    });