简体   繁体   English

角度$ scope与$ watch的混淆

[英]Angular $scope confusion with $watch

I'm still in the beginning stages of my Angular 1.0 journey. 我仍处于Angular 1.0旅程的开始阶段。 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. 最近,在使用$ watch时遇到了一些麻烦,这让我感到困惑。 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. 如果我的cookie发生更改,我将发出一个事件,从而触发事件侦听器,该事件侦听器会将$ scope.userWelcome的值更改为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. 我首先尝试了此方法,但是即使我移至应用程序中的另一个页面,它也不会更改$ scope.userWelcome的值。 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: 尝试直接查看Cookie:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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