AngularJS以

时间:2016-02-26 18:20:11

标签: javascript angularjs validation angularjs-directive

我正在尝试创建一个指令,如果某个字段被禁用,它将跳过验证。

我正在使用这种方法: implementing a directive to exclude a hidden input element from validation ($addControl issue)

我的指示是:<​​/ p>

dashboardApp.directive('shownValidation', function() {
  return {
    require: '^form',
    restrict: 'A',
    link: function(scope, element, attrs,form) {
      var control;

      scope.$watch(attrs.disabled,function(value){          
        if (!control){
          control = form[element.attr("name")];
        }
        if (value == false){
          form.$addControl(control);
          angular.forEach(control.$error, function(validity, validationToken) {
             form.$setValidity(validationToken, !validity, control);
          });
        } else {
         console.log("Before remove control." + control.$name + " Form valid = " + form.$valid);
           form.$removeControl(control);
           console.log("After remove control." + control.$name + " Form valid = " + form.$valid);
        }
      });
    }
  };
});

在我的app控制器中,我有一个表格<$ p>的$有效状态

$scope.$watch("userProfileForm.$valid", function(newValue) {
    console.log("Log in controller for userProfileForm.$valid= " + newValue);
});

我在jsp中的输入声明是:

<input type = "text" name = "title" ng-disabled  = "PROFILE_DISABLED_FIELDS_TITLE" required shown-validation  />

我在页面中显示div <div>{{userProfileForm.$valid}}</div>中表单的有效状态以进行检查,因为根据$ valid状态我禁用/启用保存按钮。

以下是我打开页面时的日志:

    profile-editor-controller.js:164 Log in controller for userProfileForm.$valid= true
    pc-directives.js:460 Before remove control.title Form valid = false
    pc-directives.js:462 After remove control.title Form valid = true
    profile-editor-controller.js:164 Log in controller for userProfileForm.$valid= false

表单中还有其他输入字段有验证器,但我确保它们都是有效的,例如。

如果我在页面完全加载后在控制器中放置断点并打印控制台上的消息,我可以看到$scope.userProfileForm.$error.required[0].$name == "title" 但是,如果我看到该字段不再在表格上:

$scope.userProfileForm.title == undefined

我错的任何想法或诀窍在哪里?

稍后编辑:

在我阅读了一些关于$ watch和$ observe的文章之后,我发现这两个函数根据你的角度版本工作不同,让我尝试了不同的方法,我找到了一个解决方案:

app.directive('validIfDisabled', function() {
    return {
      require: 'ngModel',
      restrict: 'A',
      link: function(scope, element, attrs,model) {

          var disabled=false;

          function makeModelValid (model){
              angular.forEach(model.$validators, function(validatorValue, validatorKey) {
                    model.$setValidity(validatorKey,true);
                });
          }

          attrs.$observe( "disabled", function (value) {
              disabled = value;
              if(disabled){
                  makeModelValid(model);
              }else{
                  model.$validate();
              }
          }); 

          scope.$watch(function(){return model.$invalid;},function(){
              if(disabled){
                 makeModelValid(model);
              }
          });
      }
    };
  });

0 个答案:

没有答案