1

I have a directive attached to an input field that calls $compile(element)(scope); in its Link method. Everything works well, except when trying to use the following:

ng-class="{ 'has-error' : frm.first_name.$invalid && frm.last_name.$dirty }"

The $invalid property updates, but $dirty (and $pristine) always retain their initial values.

plnkr example

I'm not sure how to approach this problem. Does anyone have any ideas? Any info would be greatly appreciated. Thanks!

John Tiggernaught
  • 758
  • 1
  • 6
  • 25

1 Answers1

1

You need to use compile, instead of link like so:

  app.directive('inputDataType', ['$compile', function ($compile) {
      var compileFn = function(element) {
          element.removeAttr('input-data-type');

          // Add pattern
          element.attr('ng-pattern', '^[a-zA-Z0-9]+$');

          // Make input field required
          element.attr('required', 'true');

          // Compile to attach new directives / pattern / required
          var fn = $compile(element);

          return function(scope){
              fn(scope);
          };
      };

      return {
          restrict: 'A',
          scope: false,
          terminal: true,
          priority: 1001,
          compile: compileFn
      };
  }]);

Look here for more info: creating a new directive with angularjs

Updated plunkr: http://plnkr.co/edit/85uHw9pSS3dEy9dGX2lz

Community
  • 1
  • 1
Kevin F
  • 2,836
  • 2
  • 16
  • 21
  • Thanks for taking a look. Unfortunately, now the $invalid property doesn't update (but $dirty / $pristine are now working as expected). – John Tiggernaught Jun 08 '15 at 17:44
  • Updated plunkr again, and updated code in answer. Forgot that for compile element is the first param so the code was erroring! Seems to work for me now – Kevin F Jun 08 '15 at 18:05
  • Sorry to be a pain, I have an updated [plunker](http://plnkr.co/edit/3cDNbk7OBxjBtfIktN2V?p=preview) that includes changes noted in your ['more info'](http://stackoverflow.com/questions/21315312/creating-a-new-directive-with-angularjs/21317635#21317635) link and used ng-pattern but I'm still having issues. Could I trouble you for any more advice? – John Tiggernaught Jun 08 '15 at 18:17
  • @ Kevin F Thanks for your time, everything appears to be working now! Updated [Plunker](http://plnkr.co/edit/3cDNbk7OBxjBtfIktN2V?p=preview) for prosperity. – John Tiggernaught Jun 08 '15 at 18:26