【问题标题】:angular - Dynamically changing validation requirements between form elements in directivesangular - 指令中表单元素之间动态变化的验证要求
【发布时间】:2014-09-17 18:25:29
【问题描述】:

我有一个包含许多表单输入的表单。所有表单输入都在指令中。

在某些情况下,我需要一个元素的状态来影响其他表单元素的属性,例如 ng-required。

我很难弄清楚如何更新其他表单元素中的 ng-required 字段/$valid - 它们保持在 $valid = false 的状态 - 我想动态更改 ng-required 值为 false,因此不再需要它们并且元素变为有效。

在下面/在 plnkr 的场景中,如果您在第一个 Title 元素中键入文本,则不再需要第二个元素 Title2,但它仍保持为 $valid=false。

我尝试使用传递给指令的函数,如下所示,但它似乎没有更新表单元素的有效性...

Plnkr! http://plnkr.co/edit/gCpB7dvBjiOisocjJNlz?p=preview

$scope.toggleRequired = function(content, contentFragment){
    if (contentFragment.name =='title' && angular.isDefined(contentFragment.value) && contentFragment.value.length){
      $scope.content.title2.required=false;      
      content.title2.required=false;      
    }else if (contentFragment.name =='title' && !angular.isDefined(contentFragment.value)){
      $scope.content.title2.required=true;      
      content.title2.required=true;      
    }
  }

【问题讨论】:

    标签: forms angularjs validation dynamic angularjs-directive


    【解决方案1】:

    ng-required实际上接受一个表达式,所以不需要在变量周围加上{{ .. }},否则表达式在编译时只会被计算一次。

    textFormElement.html 模板中,更改这一行:

    ng-required="{{contentFragment.required}}"
    

    到这里:

    ng-required="contentFragment.required"
    

    Plunker: http://plnkr.co/edit/YLInikMU5Dl2hIpHPauy?p=preview

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2016-11-28
      • 1970-01-01
      • 2018-02-20
      • 1970-01-01
      • 2019-08-11
      • 1970-01-01
      • 2014-08-20
      • 2018-04-24
      • 2017-09-05
      相关资源
      最近更新 更多