-
-
Save katowulf/eb8f9c24629f6a04464b to your computer and use it in GitHub Desktop.
Separate auth and sync logic
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
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