angularjs – 带有unix时间戳的ui bootstrap datepicker

前端之家收集整理的这篇文章主要介绍了angularjs – 带有unix时间戳的ui bootstrap datepicker前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用ui-bootstrap datepicker绑定到unix时间戳数据.

为此,我想使用this directive将unix时间戳转换为ng-model的javascript日期.

here is the code (plunker)

<div ng-model="date" date-format>
    <datepicker min="minDate" show-weeks="false"></datepicker>
</div>

和指令

.directive('dateFormat',function() {
        return {
              require: 'ngModel',link: function(scope,element,attr,ngModelCtrl) {
                    ngModelCtrl.$formatters.unshift(function(timestamp) {
                          if (timestamp) return new Date( timestamp * 1000 );
                          else return "";
                    });
                    ngModelCtrl.$parsers.push(function(date) {
                          if (date instanceof Date) return Math.floor( date.getTime() / 1000 ); 
                          else return "";
                    });
              }
        };
  })

可以选择日期. unix时间戳是正确的但是,日历切换到1970 …

是否有解决方案使这项工作和使用ui bootstrap的datepicker与unix时间戳数据?

这有点晚了,但我也有这个问题 – 我不想在我的模型中为datepicker / timepicker保留额外的价值.跟随Christopher Nadeau跟随 this great tutorial on ngModelController

这适用于AngularJS 1.2.16:

.directive('timestampFormat',function() {
    // Directive that converts timestamp back and forth from
    // seconds to Date object
    return {
        scope: true,// isolated scope
        require: 'ngModel',ngModelCtrl) {

            ngModelCtrl.$formatters.push(function (modelValue) {
                // returns $viewValue
                return {
                    timestamp: (modelValue ? new Date(modelValue*1000) : "")
                };
            });

            scope.$watch('timestamp',function () {
                ngModelCtrl.$setViewValue({ timestamp: scope.timestamp });
            });

            ngModelCtrl.$parsers.push(function (viewValue) {
                // returns $modelValue
                if (viewValue.timestamp instanceof Date) return Math.floor( viewValue.timestamp.getTime() / 1000 );
                else return "";
            });

            ngModelCtrl.$render = function () {
                // renders timestamp to the view.
                if (!ngModelCtrl.$viewValue) ngModelCtrl.$viewValue = { timestamp: ""};
                scope.timestamp = ngModelCtrl.$viewValue.timestamp;
            };
        }
    };
});

现在,您可以将其作为时间戳变量访问.

<div ng-model="yourModelValue" timestamp-format> 
  {{timestamp}}
  <timepicker ng-model="timestamp" ...>

猜你在找的Angularjs相关文章