Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
542 views
in Technique[技术] by (71.8m points)

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

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

<div class="text-input" ng-class="{typing : (loginForm.test.$dirty || loginForm.test.length > 0)}">
  <span>Username</span>
  <input type="text" name="test" ng-model="user.name" placeholder="test">
  </div>

However when I try and make this into a directive, the ng-class part of it stops working. Can anyone help me to get it working?

Directive:

 angular.module('myApp').directive('smartInputElement',function(){
 return {
   restrict: 'E',
   require: 'ngModel',
   compile: function(element, attrs) {
   element.replaceWith('<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="ngModel" placeholder="'+attrs.name+'"></div>');
   }

 }

});

The html for the directive is:

 <smart-input-element name="username" formName="loginForm" label="Username" ng-model="username"></smart-input-element>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

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);
      };

    }
  };
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...