In my sign-in form, I am facing an issue with handling errors. The form slides in from the left using a custom directive. However, when I try to slide it out of sight, I need the current error to disappear as well. I have tried using a $watch function to monitor changes in the sharedInfo.getError() service function. Unfortunately, the $watch function only runs once when the controller loads and then stops listening for further changes. I have used similar methods successfully in the past, so I am struggling to figure out why it is not working now. Any help in identifying the problem would be greatly appreciated.
Here is the code for the controller:
forumApp.controller('signinCtrl', ['$scope', 'fbRef', 'validation', 'userLogic', 'sharedInfo', function($scope, fbRef, validation, userLogic, sharedInfo) {
$scope.$watch('sharedInfo.getError()', function(newValue, oldValue) {
console.log(oldValue);
console.log(newValue);
$scope.error = newValue;
});
$scope.user = {
email: '',
password: ''
}
$scope.validate = function() {
$scope.error = validation.validateSignin($scope.user, $scope.error);
if ($scope.error) {
return false;
}
else {
userLogic.signinUser($scope.user).then(function(authData) {
sharedInfo.setAuthState(authData);
}).catch(function(error) {
switch (error.code) {
case 'INVALID_USER':
$scope.error = 'Invalid email';
sharedInfo.setError($scope.error);
break;
case 'INVALID_EMAIL':
$scope.error = 'Invalid email format';
sharedInfo.setError($scope.error);
break;
case 'INVALID_PASSWORD':
$scope.error = 'Invalid password';
sharedInfo.setError($scope.error);
break;
}
});
}
}
}]);
The sharedInfo service which manages shared information across controllers:
forumApp.service('sharedInfo', [function() {
var authState;
var error;
return {
getAuthState: function() {
return authState;
},
setAuthState: function(authData) {
authState = authData;
},
getError: function() {
return error;
},
setError: function(newError) {
error = newError;
}
}
}]);
The directive responsible for sliding the form in and out:
forumApp.directive('mySigninSlide', ['sharedInfo', function(sharedInfo) {
return {
restrict: 'A',
link: function($scope, element, attrs) {
element.on('click', function() {
var sidebar = $('#signin-wrapper');
if ($scope.isAnimated === undefined ||
$scope.isAnimated === false) {
sidebar.stop().animate({left: '340px'});
$scope.isAnimated = true;
}
else {
sidebar.stop().animate({left: '-606px'});
$scope.isAnimated = false;
sharedInfo.setError('');
}
});
}
};
}]);