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

Categories

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

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

1 Answer

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

    }
  };
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...