【问题标题】:Angular - form.$dirty not updating after $compileAngular - form.$dirty 在 $compile 后不更新
【发布时间】:2015-08-23 06:30:48
【问题描述】:

我有一个指令附加到一个在其 Link 方法中调用 $compile(element)(scope); 的输入字段。一切正常,除非尝试使用以下内容:

ng-class="{ 'has-error' : frm.first_name.$invalid && frm.last_name.$dirty }"

$invalid 属性更新,但 $dirty(和 $pristine)始终保持其初始值。

plnkr example

我不确定如何解决这个问题。有没有人有任何想法?任何信息,将不胜感激。谢谢!

【问题讨论】:

    标签: angularjs compilation


    【解决方案1】:

    你需要使用编译,而不是像这样的链接:

      app.directive('inputDataType', ['$compile', function ($compile) {
          var compileFn = function(element) {
              element.removeAttr('input-data-type');
    
              // Add pattern
              element.attr('ng-pattern', '^[a-zA-Z0-9]+$');
    
              // Make input field required
              element.attr('required', 'true');
    
              // Compile to attach new directives / pattern / required
              var fn = $compile(element);
    
              return function(scope){
                  fn(scope);
              };
          };
    
          return {
              restrict: 'A',
              scope: false,
              terminal: true,
              priority: 1001,
              compile: compileFn
          };
      }]);
    

    在这里查看更多信息:creating a new directive with angularjs

    更新 plunkr:http://plnkr.co/edit/85uHw9pSS3dEy9dGX2lz

    【讨论】:

    • 感谢您的浏览。不幸的是,现在 $invalid 属性没有更新(但 $dirty / $pristine 现在按预期工作)。
    • 再次更新了 plunkr,并更新了答案代码。忘记了 for compile element 是第一个参数,所以代码出错了!现在似乎对我有用
    • 很抱歉,我有一个更新的plunker,其中包括在您的'more info' 链接中记录的更改并使用了ng-pattern,但我仍然遇到问题。能否麻烦您提供更多建议?
    • @Kevin F 感谢您的宝贵时间,现在一切正常!更新 Plunker 以求繁荣。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-18
    • 1970-01-01
    相关资源
    最近更新 更多