How to input a time into firebase with AngularFire?

别来无恙 提交于 2019-12-12 03:17:16

问题


I'd like a user to be able to submit a time into the firebase database by selecting a time from the input box.

I know how to have the user enter text into firebase based on the firebase documentation, but not how the user can enter in a time into firebase.

When I add "type="time"' to the input box (as below), the below code can no longer submit input to firebase. When it's removed, it goes back to normal.

HTML

<html ng-app="sampleApp">
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
    <script src="https://cdn.firebase.com/js/client/2.2.4/firebase.js"></script>
    <script src="https://cdn.firebase.com/libs/angularfire/1.1.3/angularfire.min.js"></script>
  </head>

  <body ng-controller="SampleCtrl">
    <ul>
      <li ng-repeat="message in messages">
        <input ng-model="message.text" ng-change="messages.$save(message)" />

        <button ng-click="messages.$remove(message)">Delete Message</button>
      </li>
    </ul>
    <form ng-submit="addMessage()">
      <input type="time" ng-model="newMessageText" />
      <button type="submit">Add Time</button>
    </form>
  </body>
</html>

AngularJS

var app = angular.module("sampleApp", ["firebase"]);

app.controller("SampleCtrl", function($scope, $firebaseArray) {
  var ref = new Firebase("https://frontier.firebaseio.com/messages");
  $scope.messages = $firebaseArray(ref);

  $scope.addMessage = function() {
    $scope.messages.$add({
      text: $scope.newMessageText
    });
  };

});

How do you submit a time into firebase?

See my codepen here


回答1:


A few things are going on here:

  • An input of type text (the default type for an input) will return a string
  • An input of type time will return a Date object
  • Firebase stores JSON data
  • There is no JSON data type for Date objects

So you will have to convert the time you get into a supported type, before passing it to Firebase.

$scope.addMessage = function() {
  $scope.messages.$add({
    text: $scope.newMessageText.toString()
  });
};

Note that storing a date as a string is great if you want to only display the date. But if you want to also manipulate it (e.g. filter based on the date), you will probably want to store it as a timestamp:

$scope.addMessage = function() {
  $scope.messages.$add({
    text: $scope.newMessageText.toString(),
    timestamp: $scope.newMessageText.getTime(),
  });
};


来源:https://stackoverflow.com/questions/33194977/how-to-input-a-time-into-firebase-with-angularfire

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!