At the start of my Angular 1.0 journey, I'm gradually getting the hang of it, but some aspects still have me puzzled.
Recently, while working with $watch, I encountered a perplexing issue. Here's the snippet in question:
$scope.$watch('cookies', function() {
if ($cookies.getAll().redditSession) {
$scope.$emit('cookiesChanged')
// $scope.userWelcome = cookieService.decodeCookie($cookies.get('redditSession'))
}
})
$scope.$on('cookiesChanged', function() {
$scope.userWelcome = cookieService.decodeCookie($cookies.get('redditSession'))
})
This segment of code functions as intended. When my cookies change, I emit an event that triggers an event listener to update the value of $scope.userWelcome with data from the cookie. This change is reflected when navigating to a different route within my application.
Nevertheless, I find myself questioning why an event emitter was necessary in this scenario. The line I commented out was my initial approach, but it failed to update $scope.userWelcome even after changing routes. Only by reloading the page could I see that I was logged in.
What's the underlying reason behind this behavior?