从Firebase,angularJS检索日期 [英] Retrieve date from Firebase, angularJS

查看:126
本文介绍了从Firebase,angularJS检索日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Firebase 2.0.4 AngularFire 0.9.0

我有在编辑器中从Firebase中检索日期时出错。

I'm having trouble retrieving a date from Firebase in an editor.

首先,让我告诉你如何保存它。我意识到Firebase不会采用日期类型,所以在推送它时将其转换为字符串。

First of all, let me show you how I saved it. I realize that Firebase won't take a date type, so I convert it to a string when pushing it.

$scope.AddPost = function () {
        var title = $scope.article.title;
        var tech  = $scope.article.tech;
        var date  = $scope.article.date;
        var post  = $scope.article.post;

        var firebaseObj = new Firebase("https://xxxxxxxx.firebaseio.com/articles");
        var fb = $firebase(firebaseObj);

        fb.$push({
            title: title,
            tech: tech,
            date: date.toString(),
            post: post,
            emailId: CommonProp.getUser()
        }).then(function (ref) {
            console.log("ref: "+ref);
            $location.path('/welcome');
        }, function (error) {
            console.log("Error:", error);
        });
    };

注意 date:date.toString(), line。

它将日期保存在Firebase中,如下所示:2016-01-07T05:00:00.000Z

It saves the date in Firebase like so: "2016-01-07T05:00:00.000Z"

现在,我有一个内置于Bootstrap模态的编辑器。

Now, I have an editor that is built into a Bootstrap modal.

如上所述,我有从数据库检索其他项目没有问题,但我不知道如何在日期输入字段中显示日期。

As you can see above, I have no problem retrieving the other items from the database, but I'm not sure how to get the date to show up in the date input field. Only the placeholder shows up in the date input field.

更新
这是 editPost 更新功能。

editPost函数从数据库中检索数据... update函数将数据的更改推回数据库。

The editPost function retrieves the data from the database... the update function pushes the changes to the data back into the database.

.controller('WelcomeCtrl', ['$scope', '$firebase', 'CommonProp', function ($scope, $firebase, CommonProp) {
    $scope.username = CommonProp.getUser();
    var firebaseObj = new Firebase("https://12202015.firebaseio.com/articles");


    var sync = $firebase(firebaseObj);

    $scope.articles = sync.$asArray();

    $scope.editPost = function (id) {
        console.log(id);
        var firebaseObj = new Firebase("https://12202015.firebaseio.com/articles/" + id);

        var syn = $firebase(firebaseObj);

        //$scope.postToUpdate.date = new Date( snapshot.val().date );
        console.dir("$syn: "+ syn.date);

        $scope.postToUpdate = syn.$asObject();

        $('#editModal').modal();
    };

    $scope.update = function () {
        console.log($scope.postToUpdate.$id);
        var fb = new Firebase("https://12202015.firebaseio.com/articles/" + $scope.postToUpdate.$id);
        var article = $firebase(fb);
        article.$update({
            title: $scope.postToUpdate.title,
            tech: $scope.postToUpdate.tech,
            date: $scope.postToUpdate.date,
            post: $scope.postToUpdate.post,
            emailId: $scope.postToUpdate.emailId
        }).then(function (ref) {
            console.log(ref.key()); // bar
            $('#editModal').modal('hide');
        }, function (error) {
            console.log("Error:", error);
        });
    };


    $scope.confirmDelete = function (id) {
        var fb = new Firebase("https://12202015.firebaseio.com/articles/" + id);
        var article = $firebase(fb);
        $scope.postToDelete = article.$asObject();
        $('#deleteModal').modal();
    };

    $scope.deletePost = function () {
        var fb = new Firebase("https://12202015.firebaseio.com/articles/" + $scope.postToDelete.$id);
        var article = $firebase(fb);
        article.$remove().then(function (ref) {
            $('#deleteModal').modal('hide');
        }, function (error) {
            console.log("Error:", error);
        });
    };

    $scope.logout = function(){
        CommonProp.logoutUser();
    };

}]);

这是我的编辑模式:

<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                        <h4 class="modal-title" id="editModalLabel">Update Post</h4>
                    </div>
                    <div class="modal-body">
                        <form role="form">
                            <div class="form-group">
                                <label for="recipient-name" class="control-label">Title:</label>
                                <input type="text" class="form-control" ng-model="postToUpdate.title" id="recipient-name">
                            </div>
                            <div class="form-group">
                                <label for="recipient-name" class="control-label">Technology:</label>
                                <input type="text" class="form-control" ng-model="postToUpdate.tech" id="recipient-name">
                            </div>
                            <div class="form-group">
                                <label for="recipient-name" class="control-label">Completion Date:</label>
                                <input type="date" class="form-control" ng-model="postToUpdate.date" id="recipient-name">
                            </div>
                            <div class="form-group">
                                <label for="message-text" class="control-label">Post:</label>
                                <textarea class="form-control" id="message-text" ng-model="postToUpdate.post"></textarea>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        <button type="button" class="btn btn-primary" ng-click="update()">Publish</button>
                    </div>
                </div>
            </div>
        </div>

这个 date:new Date($ scope.postToUpdate.date) code>显然不行。

This date: new Date($scope.postToUpdate.date) obviously does not work.

推荐答案

请参阅扩展工厂。使用$$更新方法在从服务器更新时转换数据,并使用toJSON方法将本地数据转换回服务器。

See extending factories. Use the $$updated method to transform data when updated from the server, and the toJSON method to transform local data before saving it back to the server.

一个工作小提琴此代码可以在这里找到。

A working fiddle of this code can be found here.

<button ng-click="setDate(book)">update the date</button>

<h2>Formatted</h2>
{{book.title}}<br />
{{book.author}}<br />
{{book.date|date:"medium"}}<br />

<h2>Raw</h2>
<pre>{{book|json}}</pre>

// reference to our Firebase instance
var fb = new Firebase('https://kato-sandbox-books.firebaseio-demo.com/book1');

/**
 * Our Angular module and controller
 */
var app = angular.module('app', ['firebase']);
app.controller('ctrl', function ($scope, Book) {    
    // create a synchronized array with a customized version 
    // of $FirebaseArray
    $scope.book = new Book(fb);

    // changes the date on a book record, note that we're working
    // with Date objects here
    $scope.setDate = function(book) {
        book.date = new Date();
        book.$save();
    };
});

/**
 * Add a Book factory object which parses dates
 */
app.factory('Book', function ($firebaseObject) {
    return $firebaseObject.$extend({
        /**
         * Called each time there is an update from the server
         * to update our Book data
         */
        $$updated: function (snap) {
            // call the super
            var changed = $firebaseObject.prototype
                .$$updated.apply(this, arguments);
            // manipulate the date
            if( changed ) {
               this.date = new Date(this.date||0);
            }
            // inform the sync manager that it changed
            return changed;
        },

        /**
         * Used when our book is saved back to the server
         * to convert our dates back to JSON
         */
        toJSON: function() {
            return angular.extend({}, this, {
                // revert Date objects to json data
                date: this.date? this.date.getTime() : null
            });
        }
    });
});

这篇关于从Firebase,angularJS检索日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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