Skip to content

Instantly share code, notes, and snippets.

@katowulf
Created January 13, 2015 15:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save katowulf/eb8f9c24629f6a04464b to your computer and use it in GitHub Desktop.
Save katowulf/eb8f9c24629f6a04464b to your computer and use it in GitHub Desktop.
Separate auth and sync logic
app.controller('TestCtrl', ['$scope', 'getAuth', 'getAllPosts', function($scope, Auth, getAllPosts) {
Auth.$onAuth(function(user) {
if( user ) {
$scope.posts = getAllPosts();
}
else {
purgePosts();
}
});
// clean up posts when the controller is unloaded
$scope.$on('$destroy', purgePosts);
function purgePosts() {
if( $scope.posts ) {
$scope.posts.$destroy();
}
}
}];
app.factory('getAllPosts',['$firebase', 'ref', function ($firebase, ref) {
return function() {
// always return a new instance so the list can be renewed
return $firebase(ref('posts')).$asArray();
};
}]);
app.factory('Auth', ['$firebaseAuth', 'ref' ,
// auth remains a singleton
return $firebaseAuth(ref());
]);
// a simple abstraction for creating Firebase references
app.factory('ref', ['FIREBASE_URL', '$window', function(URL, $window) {
// takes any number of strings representing paths to join
return function(path) {
var ref = new $window.Firebase(URL);
if( arguments.length ) {
ref = ref.child( Array.prototype.slice.call(arguments, 0).join('/') );
}
return ref;
}
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment