AngularFire $FirebaseObject.$extendFactory example with Date objects

AngularFire $extendFactory example with Date objects for $FirebaseObject

by Kato Richardson

HTML

<script src="https://cdn.firebase.com/js/client/2.2.2/firebase.js"></script>
<script src="https://cdn.firebase.com/libs/angularfire/1.0.0/angularfire.min.js"></script>
<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>

CSS

pre {
    padding: 20px;
    font-size: 16px;
    line-height: 20px;
    background-color: #fafafa;
    border: 1px solid #999;
    display: block;
    border-radius: 10px;
    white-space: pre-wrap;
    /* css-3 */
    white-space: -moz-pre-wrap;
    /* Mozilla, since 1999 */
    white-space: -pre-wrap;
    /* Opera 4-6 */
    white-space: -o-pre-wrap;
    /* Opera 7 */
    word-wrap: break-word;
    /* Internet Explorer 5.5+ */
}
.error {
    color: red;
}

JavaScript

// 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, BookFactory) {    
    // create a synchronized array with a customized version 
    // of $FirebaseArray
    $scope.book = new BookFactory(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('BookFactory', 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
            });
        }
    });
});

/*********
 RESET DEMO DATA EACH TIME THE PAGE LOADS
 *********/
fb.set({
    title: "Grapes of Wrath",
    author: "John Steinbeck",
    date: Date.now() - 3600 * 1000 * 24 * 72 // 72 days ago
});