0

I'm using Firebase 2.0.4 and AngularFire 0.9.0.

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

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);
        });
    };

Notice the date: date.toString(), line.

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

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

enter image description here

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.

UPDATE This is the editPost and update functions.

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();
    };

}]);

This is my edit modal:

<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>

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

Livi17
  • 1,620
  • 3
  • 25
  • 43

2 Answers2

1

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
            });
        }
    });
});
Kato
  • 40,352
  • 6
  • 119
  • 149
0

You are formatting the date too late (when submitting the edit/update). i recommend to put new Date( dateVariable ) while you are fetching the data. Something like this:

$scope.postToUpdate = new Date( snapshot.val().date );

Here's a jsbin to show it should work like this.


edit: i think it should work like this:

$scope.postToUpdate = syn.$asObject();
$scope.postToUpdate.date = new Date($scope.postToUpdate.date); //add this line
nicfo
  • 450
  • 4
  • 12
  • I tried your solution in my "editPost" function which fetches the data... however, I get the following error: `ReferenceError: snapshot is not defined`. I have updated my post above to include the "editPost" function as it was not there previously. – Livi17 Jan 07 '16 at 23:27
  • do you mind posting the code where you retrieve the data from firebase? – nicfo Jan 07 '16 at 23:40
  • I edited my question above to include the entire controller. Within that controller the "editPost" function is what retrieve's the data from firebase for the edit modal. – Livi17 Jan 07 '16 at 23:50
  • oh, sorry i assumed you fetched the data with a value event, my bad.. i'll edit my answer, it's getting confusing in the comments.. – nicfo Jan 08 '16 at 00:03
  • I tried your suggestion, but it gets the error: **Error: [ngModel:datefmt] Expected `Sat Mar 02 1901 00:00:00 GMT-0500 (EST)` to be a date** – Livi17 Jan 08 '16 at 01:53