【问题标题】:How to get ng-class with $dirty working in a directive?如何让 $dirty 在指令中工作的 ng-class?
【发布时间】:2014-03-08 08:42:44
【问题描述】:

当使用 $dirty 更改输入时,我有以下 html 可以工作并更改 div 的类:

<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>

但是,当我尝试将其作为指令时,它的 ng-class 部分停止工作。谁能帮我让它工作?

指令:

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

 }

});

指令的html是:

 <smart-input-element name="username" formName="loginForm" label="Username" ng-model="username"></smart-input-element>

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    这里是一个笨蛋:http://plnkr.co/edit/3AFOHZFgExZKHjnd3gb0?p=preview

    当你在编译函数中替换一个元素时,你应该:

    指令:

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

    【讨论】:

    • 非常感谢您的帮助。这行得通。我花了太多时间在这上面,并没有完全弄清楚问题可能是什么。
    • 只是跟进 - Ilan,你认为这是最好的方法吗?是否有另一种在指令中实现这一点的方法比使用 compile 更好?
    猜你喜欢
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 2016-12-18
    • 2018-03-19
    • 1970-01-01
    • 2014-02-11
    • 1970-01-01
    • 2014-05-08
    相关资源
    最近更新 更多