title: Angular Directive: Adding ng-class directive at compile time on existing template element
body: <p><strong>Long story short, the idea is to simplify templating by not having to manually add <code>ng-class={'has-error': 'formName.inputName.$invalid'}</code> on every single <code>form-group</code></strong></p>
  
  <p>So I want to create a directive that will generate a string that will be added to a template element. That string is an <code>ng-class</code> attribute with an expression</p>
  
  <p>I thought that creating a quick directive that adds the ng-class attribute during the compile phase would be enough, but it doesn't seem to cut it.</p>
  
  <h2>Directive Definition Object</h2>
  
  <pre><code>{
      restrict: 'C',
      compile: function(tElement, tAttrs) {
          var $elem = angular.element(tElement),
              formName = $elem.parents('[ng-form]').length ? $elem.parents('[ng-form]').attr('ng-form') : $elem.parents('form').attr('name'),
              controlName = $elem.find('.form-control').attr('name');
  
          $elem.attr('ng-class', '{"has-error": ' + formName + '.' + controlName + '.$invalid}');
  
          console.log('added ng-class attr', $elem.attr('ng-class'));
      }
  }
  </code></pre>
  
  <h2><a href="http://plnkr.co/edit/n1jf5FPtAzueLnELaQcO?p=preview" rel="noreferrer">Plunk here</a></h2>
  
  <p>See the console</p>
  
  <blockquote>
    <p>The 1st <code>form-group</code> has its <code>ng-class</code> attribute added dynamically.<br>
    The expression associated with it is correct<br>
    But the <code>ng-class</code> directive is never executed</p>
    
    <p>The 2nd <code>form-group</code> has its <code>ng-class</code> attribute added manually in the template and works as expected, obvisouly</p>
  </blockquote>
  
  <p>--</p>
  
  <p>What am I missing here?</p>