简体   繁体   中英

Angular $scope confusion with $watch

I'm still in the beginning stages of my Angular 1.0 journey. I'm learning to like it, but I'm still scratching my head in a few places.

Lately, I've run into something while using $watch that's left me confounded. Take a look:

$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 code works. If my cookies change, I emit an event thereby triggering the event listener, which changes the value of $scope.userWelcome to some value stored in the cookie. I see this change if I navigate to another route in my app.

However, I'm wondering why I had to use an event emitter here? Notice the line I commented out. I tried this first, but it doesn't change value of $scope.userWelcome, even if I move to another page in my app. I have to reload the page in order to see that I'm logged in.

What's going on here?

Your mistake is that you try to get the new value with the standard method. The way you can actually get the new value is adding it to the parameters of the function. Here it goes:

$scope.$watch('cookies', function(newValue, oldValue) {
  if (newValue.getAll().redditSession) {
    $scope.userWelcome = cookieService.decodeCookie(newValue.get('redditSession'))
  }
  // also try this
  console.log(oldvalue === $cookies);
});

Cheers!

Try watching the cookie directly:

$scope.$watch(
    function () {
        return $cookies.get('redditSession');
    },
    function (newValue) {
        if (newValue) { 
            $scope.userWelcome = cookieService.decodeCookie(newValue); 
        };
    }
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM