Skip to content

Instantly share code, notes, and snippets.

@amazari
Created April 19, 2013 08:13
Show Gist options
  • Save amazari/5418870 to your computer and use it in GitHub Desktop.
Save amazari/5418870 to your computer and use it in GitHub Desktop.
'use strict';
angular.module('firebase', []).value('Firebase', Firebase);
// Implicit syncing. angularFire binds a model to $scope and keeps the dat
// synchronized with a Firebase location both ways.
// TODO: Optimize to use child events instead of whole 'value'.
angular.module('firebase').factory('angularFire', ['$q', function($q) {
return function(url, scope, name, ret) {
var af = new AngularFire($q, url);
return af.associate(scope, name, ret);
};
}]);
function AngularFire($q, url) {
this._fRef = new Firebase(url);
}
AngularFire.prototype = {
associate: function($scope, name, ret) {
var self = this;
if (ret == undefined) {
ret = [];
}
this._fRef.on('value', function(snap) {
if (snap && snap.val() != undefined) {
var val = snap.val();
}
self._safeApply($scope,
function() { $scope[name] = val; });
});
return '';
},
_watch: function($scope, name) {
// Watch for local changes.
var self = this;
$scope.$watch(name, function() {
var val = JSON.parse(angular.toJson($scope[name]));
if (angular.equals(val, self._remoteValue)) {
return;
}
self._fRef.set(val);
}, true);
},
_safeApply: function($scope, fn) {
var phase = $scope.$root.$$phase;
if (phase == '$apply' || phase == '$digest') {
fn();
} else {
$scope.$apply(fn);
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment