angularjs - 比较两个日期的指令

标签 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('lowerThan', false);第一次让它不可见。但它不起作用。

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

最佳答案

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

  • 删除 $attrs.$observe
  • 创建并应用 higherThan指向其他字段的指令
  • 告诉您的指令不适用于模型值($formatters 数组),而仅适用于输入值($parsers 数组)。

  • 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>
    

    关于angularjs - 比较两个日期的指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23308956/

    相关文章:

    javascript - AngularJS - 动态 DOM 操作,无需在 Controller 中硬编码 dom id

    angularjs - 如何从父范围检查包含 ng 的表单的有效性?

    html - 如何在angularJS中将数据放入数组?

    javascript - 单击页面任意位置时如何调用 AngularJS 指令的函数?

    javascript - 调用另一个指令的模板指令

    javascript - 如何在 div 等其他元素上使用 Angular 表单验证?

    javascript - 无法使用 ng-click 更改 Angular $scope

    javascript - 如何为一个元素设置多个类

    angularjs - Angular 引导评级

    javascript - 没有接收到我的工厂发出的 $rootScope 事件