在AngularFire上实时,实时3种方式进行数据绑定日期时间输入 [英] Live, realtime 3 ways data-binding date-time input on AngularFire

查看:74
本文介绍了在AngularFire上实时,实时3种方式进行数据绑定日期时间输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下简化的代码版本:

I have the following simplified version of my code:

tr(ng-repeat='entry in ds3.entries | orderBy:orderByField:reverseSort | filter:query as results')        
    td
      input.screen(type='datetime-local', ng-model='entry.date_received', datetime="MM/dd/yyyy hh:mm a" )
      span(ng-hide='') {{entry.date_received | dateFormat }}
tr.screen
    td
      input.screen(type='datetime-local', ng-model='new_entry.date_received', datetime="MM/dd/yyyy hh:mm a", date-parser="MM/dd/yyyy hh:mm a")
    td
      button.btn-xs.btn-success(ng-click='insert()')
        span.fa.fa-plus-square
        |   Insert

这是HTML视图的Jade部分,据称可以添加新的日期时间本地数据并实时更新(如GoogleDocs Excel表).

That is the Jade part for HTML view, allowing supposedly adding new datetime-local data and updating it live (like an GoogleDocs Excel table).

我正在尝试使用AngularFire(AngularJS 1.x和Firebase数据库)连接.我已经能够使用Auth,并且在文本输入字段中也可以使用.问题是,我们知道Firebase不接受DATETIME值.因此,我正在尝试针对集合使用 3向数据绑定进行实时,实时更改和编辑日期时间输入的替代方案和解决方法.

I'm trying to wire things up using AngularFire (AngularJS 1.x and Firebase database). I had been able to have Auth and things worked for text input field. Problem is as we know Firebase doesn't accept DATETIME value. So, I'm trying to sort out alternatives and workaround solutions for live, realtime changing and editing of datetime input using 3-ways data binding for a collection.

我的 计划 是将日期时间作为整数字符串(unix_timestamp)发送到Firebase,并以日期时间格式.因此,我尝试了2条指令.

My planning is to have datetime sent to Firebase as integer string (unix_timestamp) and feed back as a datetime format. So, I try 2 directives.

1-用于过滤视图的整数显示结果.

1- to filter display result from integer string for the view.

angular.module('workspaceApp')
.filter('dateFormat', ['$moment', function($moment) {
    return function(time) {
      return time ? $moment.unix(time).format('MM/DD/YYYY - hh:mm a') : time;
    };
}])

2-(艰难的人)-将整数字符串转换并保存到Firebase数据库,而不会在视图上显示错误(因为在3向数据绑定[概念]中将事物捆绑在一起,所以我一直在努力寻找方法正确地做).对于文本字段,我只会在输入标签中执行ng-change ='ds3.entries.$ save(entry)'.

2-(tough one)- to convert and save integer string to Firebase database without showing error on the view (because things tied together in 3-ways data binding [concept] so I'm stucked and struggling at figuring out how to do it properly). For text field, I would only do ng-change='ds3.entries.$save(entry)' in the input tag.

.directive("input", function () {
return {
    require: 'ngModel',
    /* scope : {
                   entries : "="
    },*/
    link: function (scope, elem, attr, modelCtrl) {
      if (attr['type'] === 'date' || attr['type'] === 'datetime-local') {
        modelCtrl.$formatters.push(function (modelValue) {
          if (modelValue) {
              return new Date(modelValue * 1000);
          } else {
              return null;
          }
        });
        elem.bind('change', function () {
          scope.$apply(function() {
            var str = elem.val();
            var time = new Date(elem.val());
            var unix_time = Math.floor(time.getTime() / 1000);
            console.log(str, unix_time);
            scope.entries.$save().then(function(ref) {
              ref.key() === scope.entry.$id; // true
            }, function(error) {
              console.log("Error:", error);
            });
            modelCtrl.$setViewValue(unix_time.toString());
            modelCtrl.$render();
            // $scope.entry.update(unix_time.toString());
          });
        });
      }
    }
};

})

.directive('fetchDate', function(){
return {
  link: function($scope){
    $scope.$watch('date_received', function(newVal, oldVal){
      if (newVal){
        $scope.entry.date_received = Math.floor(newVal / 1000);
        console.log($scope.entry.date_received);
      }
    });
  }
};

})

我在日期时间输入中使用了ng-change = UpdateFunction(),并转到指令和控制器来编写函数,但尚未解决.我也尝试过$ watch,但通常在控制台中看到的是旧日期还是新日期.

I went with ng-change=UpdateFunction() in the datetime input and went to directive and controller to write the function but not yet solve it. I tried $watch too but usually see undefined either old date or new date in the console.

$scope.$watch('entry.date_received',function(newVal, oldVal){
  console.log(Math.floor(newVal / 1000) , Math.floor(oldVal / 1000));
  // $scope.update(newVal);
});

但是很难解决.有什么想法吗?

But hardly get it solved. Any ideas?

推荐答案

将其放在您的<input type="date" date-conversion/>上将处理AngularFire和日期的三向绑定.

Putting this on your <input type="date" date-conversion/> will handle 3 way binding with AngularFire and dates.

app.directive('dateConversion', function () {
return {
    restrict: "A",
    require: "ngModel",
    link(scope, element, attributes, ngModel) {
        ngModel.$formatters.push(value => {
            let output = null;
            if (value) {
                scope.stringValue = value;
            }
            if (value) { output = moment(value).toDate(); }
            return output;
        });

        ngModel.$parsers.push(value => {
            let output = null;
            if (value) { output = moment(value).format(); }
            return output;
        });
    },
}

});

这篇关于在AngularFire上实时,实时3种方式进行数据绑定日期时间输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆