Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
507 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 Reply

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

    }
  };
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...