Angular Directive用于比较datetimepicker中的2个日期

时间:2015-09-16 04:47:27

标签: angularjs unit-testing angularjs-directive

我写了这个指令来比较2个日期。这些日期由datetimepicker插入。

angular.module('core').directive('greaterThan', [
    function () {

        var link = function ($scope, $element, $attrs, ctrl) {

            var validate = function (viewValue) {

                var comparisonModel = $attrs.greaterThan;

                if (typeof viewValue === 'undefined' && !comparisonModel) {
                    ctrl.$setValidity('greaterThan', true);
                }

                if (typeof viewValue === 'object' && !comparisonModel) {
                    ctrl.$setValidity('greaterThan', Date.now() < viewValue.getTime());
                }

                if (typeof viewValue === 'object' && comparisonModel) {
                    // Format: "2015-09-15T07:00:00.000Z"
                    var dateTime = comparisonModel.replace(/"/g, '');
                    var myDate = new Date(Date.parse(dateTime));         
                    ctrl.$setValidity('greaterThan', myDate.getTime() < viewValue.getTime());
                }

            return viewValue;
        };

        ctrl.$parsers.unshift(validate);

        $attrs.$observe('greaterThan', function (comparisonModel) {
            return validate(ctrl.$viewValue);
        });

     };

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

}]);

现在我有2个问题: 1.我的代码风格好吗?我能改进什么? 2.我如何为该指令编写测试单元?例如:我不知道如何向此指令插入值。

0 个答案:

没有答案