2014-01-16 77 views
-1

我有這些自定義驗證指令,它們按預期工作。 問題是我想觸發驗證的輸入時,用於比較的其他輸入被改變..這是可以解決的手錶塊?AngularJS自定義驗證,日期是在其他日期之前或之後

可以說我有

<input afterOtherDate="dateB" ng-model="dateA" value="2014"/> 

<input beforeOtherDate="dateA" ng-model="dateB" value="2013"/> 

如果我再設置dateA是dateB後,dateA將失效,但dateB不會知道。 同周圍的其他方法,如果我有

<input afterOtherDate="dateB" ng-model="dateA" value="2013"/> 

<input beforeOtherDate="dateA" ng-model="dateB" value="2014"/> 

兩個輸入需要重新驗證的另一個變化時。所以兩者都有效。

validationHelpers.directive('afterOtherDate', function() { 
return { 
    restrict: 'A', 
    require: 'ngModel', 
    link: function (scope, elm, attrs, ctrl) { 
     var doValidation = function() { 
      ctrl.$parsers.unshift(function (viewValue) { 
       if (viewValue <= compareTo) { 
        ctrl.$setValidity('afterOtherDate', false); 
        return viewValue; 
       } else { 
        ctrl.$setValidity('afterOtherDate', true); 
        return viewValue; 
       } 
      }); 
     }; 

     var scopeHierarchy = attrs["afterOtherDate"].split('.'); 
     var compareTo = scope; 
     for (var k = 0; k < scopeHierarchy.length; k++) { 
      compareTo = compareTo[scopeHierarchy[k]]; 
     } 

     scope.$watch(attrs["afterOtherDate"], function (val) { 

     }); 

     doValidation(); 
    } 
}; 
}); 

validationHelpers.directive('beforeOtherDate', function() { 
return { 
    restrict: 'A', 
    require: 'ngModel', 
    link: function (scope, elm, attrs, ctrl) { 
     var doValidation = function() { 
      ctrl.$parsers.unshift(function (viewValue) { 
       if (viewValue <= compareTo) { 
        ctrl.$setValidity('beforeOtherDate', true); 
        return viewValue; 
       } else { 
        ctrl.$setValidity('beforeOtherDate', false); 
        return viewValue; 
       } 
      }); 
     }; 

     var scopeHierarchy = attrs["beforeOtherDate"].split('.'); 
     var compareTo = scope; 
     for (var k = 0; k < scopeHierarchy.length; k++) { 
      compareTo = compareTo[scopeHierarchy[k]]; 
     } 

     scope.$watch(attrs["beforeOtherDate"], function (val) { 

     }); 

     doValidation(); 
    } 
}; 
}); 

在自定義指令中解決它會很酷!

BR TWD

+1

目前還不清楚你是否年工作會只(如「2014」),或在實際日期(如「01/16/2014" )?另外,當使用'ng-model'時,你不應該真正使用'value'屬性。看看這個類似的問題:[自定義表單驗證指令來比較兩個字段](http://stackoverflow.com/questions/20982751/custom-form-validation-directive-to-compare-two-fields/20984017#20984017 )。 – Stewie

+0

它的真實日期,沒有真正的代碼中的值。這些樣本有點兒僞裝。 – twDuke

+0

完美的作品。隨意添加plunker作爲答案,我會標記它。 – twDuke

回答

0

我做什麼我的指示,我得到ngModel的這我想比較領域的控制器:

var compareModel = scope.$eval([formCtrl.$name, attr.dateAfter].join(".")); 

我傳遞模型名稱在屬性中。然後你可以訪問它的解析器並推送一個方法來啓動模型中的驗證。

compareModel.$parsers.push(function (value) { 

我強迫compareModel使用$setViewValue重新驗證:

compareModel.$parsers.push(function (value) { 
    checkBefore(value); 
    model.$setViewValue(model.$viewValue); 
    return value; 
}); 
相關問題