Created
April 19, 2013 08:13
-
-
Save amazari/5418870 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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