T0mba T0mba - 1 month ago 7
AngularJS Question

AngularJS & Firebase auth ngShow and ngClick delay?

I'm just starting out with AngularJS and I'm running into an odd problem regarding Firebase authentication. I have a very simple body which shows to current user status (logged in, true or false) and a signIn and signOut option.

When I click the Log-in button the first time, nothing happens. When I click it a second time, the logged in status changes and the ng-show and ng-hide divs switch.

Same problem when clicking sign out.

Why does it only happen after the second click?

index.html:

<div class="container" ng-controller="userCtrl">

<h1>User logged in: {{loggedIn}}</h1>

<div ng-hide="loggedIn">
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" name="email" ng-model="user.email" />
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" class="form-control" name="password" ng-model="user.password" />
</div>
<button type="button" class="btn btn-lg btn-success" ng-click="signIn()">Sign in</button>
</div>
<div ng-show="loggedIn"><button type="button" class="btn btn-lg btn-danger" ng-click="signOut()">Sign out</button></div>
</div>


Controller:

var myApp = angular.module("tijdlozespelApp", ["firebase"]);

myApp.controller("userCtrl", function ($scope, $firebaseObject) {

$scope.loggedIn = false;

$scope.signIn = function() {
var email = $scope.user.email;
var password = $scope.user.password;
firebase.auth().signInWithEmailAndPassword(email, password).then(function(user) {
$scope.loggedIn = true;
}).catch(function(error) {
$scope.loggedIn = false;
});
}

$scope.signOut = function() {
firebase.auth().signOut().then(function() {
$scope.loggedIn = false;
});
}

});

Answer

Use $scope.$apply(function() {...}) to update your scope data when you use async handlers. Angular have problems with identifing scope changes for async operations.

$scope.$apply(function() {
   $scope.loggedIn = true;
});