比较两个日期的指令

时间:2014-04-26 09:22:32

标签: angularjs angularjs-directive

我使用了以下代码来比较两个日期(参考Custom form validation directive to compare two fields

define(['./module'], function(directives) {
'use strict';
directives.directive('lowerThan', [
 function() {

   var link = function($scope, $element, $attrs, ctrl) {
   ctrl.$setValidity('lowerThan', false);
   var validate = function(viewValue) {
    var comparisonModel = $attrs.lowerThan;                

    /*if(!viewValue || !comparisonModel){
      // It's valid because we have nothing to compare against
      //console.log("It's valid because we have nothing to compare against");
      ctrl.$setValidity('lowerThan', true);
    }*/

    // It's valid if model is lower than the model we're comparing against
    //ctrl.$setValidity('lowerThan', parseInt(viewValue, 10) <    parseInt(comparisonModel, 10) );        
    if(comparisonModel){       
        var to = comparisonModel.split("-");        
        var t = new Date(to[2], to[1] - 1, to[0]);
    }
    if(viewValue){
      var from=viewValue.split("-");
      var f=new Date(from[2],from[1]-1,from[0]);
    }

    console.log(Date.parse(t)>Date.parse(f));
    ctrl.$setValidity('lowerThan', Date.parse(t)>Date.parse(f));        
    return viewValue;
  };

  ctrl.$parsers.unshift(validate);
  ctrl.$formatters.push(validate);

  $attrs.$observe('lowerThan', function(comparisonModel){
    // Whenever the comparison model changes we'll re-validate
    return validate(ctrl.$viewValue);
  });

};

return {
  require: 'ngModel',
  link: link
};

 }
 ]);
 });

但是第一次加载页面时会显示错误消息。我尝试过使用ctrl。$ setValidity(&#39; lowerThan&#39;,false);使它第一次看不见。但它不起作用。

这是相同的plunker。 http://plnkr.co/edit/UPN1g1JEoQMSUQZoCDAk?p=preview

1 个答案:

答案 0 :(得分:8)

你的指示没问题。您在控制器内设置日期值,并且您将较低的日期设置为较高的值,这意味着日期在加载时无效。你的指令正确检测到了。如果您不希望您的指令在加载时验证您的数据,那么您需要三件事:

  1. 删除$ attrs。$ observe

  2. 创建higherThan指令并将其应用于其他字段

  3. 告诉您的指令不要应用于模型值($ formatters数组),而只应用于输入值($ parsers数组)。

  4. PLUNKER

    'use strict';
    var app = angular.module('myApp', []);
    
    app.controller('MainCtrl', function($scope) {
      $scope.field = {
        min: "02-04-2014",
        max: "01-04-2014"
      };
    
    });
    
    app.directive('lowerThan', [
      function() {
    
        var link = function($scope, $element, $attrs, ctrl) {
    
          var validate = function(viewValue) {
            var comparisonModel = $attrs.lowerThan;
            var t, f;
    
            if(!viewValue || !comparisonModel){
              // It's valid because we have nothing to compare against
              ctrl.$setValidity('lowerThan', true);
            }
            if (comparisonModel) {
                var to = comparisonModel.split("-");
                t = new Date(to[2], to[1] - 1, to[0]);
            }
            if (viewValue) {
                var from = viewValue.split("-");
                f = new Date(from[2], from[1] - 1, from[0]);
            }
    
            ctrl.$setValidity('lowerThan', Date.parse(t) > Date.parse(f));
            // It's valid if model is lower than the model we're comparing against
    
            return viewValue;
          };
    
          ctrl.$parsers.unshift(validate);
          //ctrl.$formatters.push(validate);
    
        };
    
        return {
          require: 'ngModel',
          link: link
        };
    
      }
    ]);
    
    app.directive('higherThan', [
      function() {
    
        var link = function($scope, $element, $attrs, ctrl) {
    
          var validate = function(viewValue) {
            var comparisonModel = $attrs.higherThan;
            var t, f;
    
            if(!viewValue || !comparisonModel){
              // It's valid because we have nothing to compare against
              ctrl.$setValidity('higherThan', true);
            }
            if (comparisonModel) {
                var to = comparisonModel.split("-");
                t = new Date(to[2], to[1] - 1, to[0]);
            }
            if (viewValue) {
                var from = viewValue.split("-");
                f = new Date(from[2], from[1] - 1, from[0]);
            }
    
            ctrl.$setValidity('higherThan', Date.parse(t) < Date.parse(f));
            // It's valid if model is higher than the model we're comparing against
    
            return viewValue;
          };
    
          ctrl.$parsers.unshift(validate);
          //ctrl.$formatters.push(validate);
    
        };
    
        return {
          require: 'ngModel',
          link: link
        };
    
      }
    ]);
    
    <form name="form" >
    
      Min: <input name="min" type="text" ng-model="field.min" lower-than="{{field.max}}" />
      <span class="error" ng-show="form.min.$error.lowerThan">
        Min cannot exceed max.
      </span>
    
      <br />
    
      Max: <input name="max" type="text" ng-model="field.max" higher-than="{{field.min}}" />
      <span class="error" ng-show="form.max.$error.higherThan">
        Max cannot be lower than min.
      </span>
    
    </form>