Let the image do the talking: http://www.youtube.com/watch?v=4jgdj8LBQRs [25 sec]
Plunker: http://plnkr.co/edit/pL3z77vmYeSZzGMSL0YV?p=preview
Firebase GUI: http://syncing.firebase-demo.io/
I'm using angular 1.2.6 (fairly recent) and AngularFire 0.6 (latest).
Steps to reproduce
- I have a list of todos that is syncing with Firebase
- I log in and local changes are propagated to Firebase
- I log out and I disassociate binding, clearing local scope
- I log in again: strange things happen (see video)
Critical fragments of code below (plunker has it all)
1. Controller
$rootScope.$watch("loginState", function() {
$scope.loginState = $rootScope.loginState;
if ($scope.loginState == "loggedIn") {
$scope.$firRef = $firebase(new Firebase($scope.firebaseURL + "testuser/todos/"));
$scope.$firRef.$bind($scope, "todos").then(function(unbind) {
$scope.unbindFunction = unbind; // I store reference to unbinding function
});
} else if ($scope.loginState == "loggedOut") {
$scope.unbindFunction(); // and call it on logout
$scope.$firRef = null // doesn't help either
$scope.todos = [];
}
});
$scope.login = function() {
loginService.login();
}
$scope.logout = function() {
loginService.logout();
}
(note that I store reference to unbind function and call it on logout)
2. Service
app.factory('loginService', ['$rootScope', function($rootScope) {
return {
login: function() {
$rootScope.loginState = "loggedIn";
},
logout: function() {
$rootScope.loginState = "loggedOut";
}
}
}]);
Docs about 3-way data binding: https://www.firebase.com/docs/angular/reference.html#bind-scope-model
Related:
- How to disassociate angularFire bound object?
- Prevent items in scope from writing to a different user's records