How to get ng-class with $dirty working in a directive?

后端 未结 1 1580
逝去的感伤
逝去的感伤 2020-12-21 16:18

I have the following html which works and changes the class of the div when the input is changed using the $dirty:

相关标签:
1条回答
  • 2020-12-21 16:46

    Here is a plunker: http://plnkr.co/edit/3AFOHZFgExZKHjnd3gb0?p=preview

    When you replace an element inside the compile function you should:

    • Manually compile & link the new template.
    • Terminate all directives on the same element.
    • Check this answer: creating a new directive with angularjs

    Directive:

    app.directive('smartInputElement', function($compile) {
      return {
        restrict: 'E',
        priority: 1001,
        terminal: true,
        compile: function(tElm, attrs) {
          var template = angular.element(
            '<div class="text-input" ng-class="{typing :  (' + attrs.formname + '.' + attrs.name + '.$dirty || ' + attrs.formname + '.' + attrs.name + '.length > 0)}">' +
            '<span>' + attrs.label + '</span>' +
            '<input type="text" name="' + attrs.name + '" ng-model="' + attrs.ngModel + '" placeholder="' + attrs.name + '">' +
            '</div>');
    
          tElm.replaceWith(template);
          var fn = $compile(template);
          return function(scope) {
            fn(scope);
          };
    
        }
      };
    });
    
    0 讨论(0)
提交回复
热议问题