Reputation: 7458
I have an angular service which manages Authentication to the app. And a controller.
service fires an even on $rootScope
when the user logs in and logs out.
I want to update the DOM element in my UI, so it shows either 'Login' or 'Logout' depending on user state.
Note that my Angular knowledge especially around events is not very good, so please feel free to give me advise on best practices.
Here's my current code.
app.service('AuthenticationService', function ($rootScope) {
var _loggedIn = "false";
this.login = function (email, password) {
if (!email || !password) return 1;
else {
_loggedIn = "true";
// broadcast on root scope, so anyone can listen
$rootScope.$broadcast("loginChanged", 1);
return 0;
}
};
this.logout = function (email, password) {
_loggedIn = "false";
// broadcast on root scope, so anyone can listen
$rootScope.$broadcast("loginChanged", 0);
}
/*other functions ommited*/
});
And in my controller
var addListener = function () {
listener = $scope.$on("loginChanged", function (e, loggedIn) {
$scope.loginButton.text = loggedIn ? "Log Out" : "Log In";
$scope.loginButton.link = loggedIn ? "#/logout" : "#/login";
console.log("loginChanged: " + loggedIn);
}); // $on returns a registration function for the listener
};
Issue is that console.log(...)
works fine, though the $scope update is not reflected in UI. I tried wrapping it in $scope.$apply
which caused in an error saying apply is already in progress.
How do I update the UI from an event ? is there a better/more standard way to achieve the same ?
Thanks In Advance
Upvotes: 2
Views: 2405
Reputation: 3444
Your code just works fine. Here is a plunker: http://plnkr.co/edit/BUOAUgOe1y3e6S2Dq6dW?p=preview
But I wouldn't use $brodcast to notify ui changes. It's like poluting your global namespace with global variables. I would recommend passing in a Service and listen for changes on that service. I've created a plunker to show you what I mean: http://plnkr.co/edit/MCWThc1ZtaAxmZSTirT6?p=preview
Upvotes: 3