Search code examples
javascriptjsonangularjswatchrootscope

$watch prevents rootScope change


I'm trying to get some JSON data to pass between controllers. I get some JSON with $http, set my callback with a $q defer and assign the result to my $rootScope.productList. Everything is working, but when I add a $watch on $rootScope.productList, it returns me undefined. Do you have any solution about this?

My $watch inside a controller:

$rootScope.watch('productList', function(newVal, oldVal) {
    $scope.filters = $rootScope.productList;
    console.log($rootScope.productList);
});

and inside another controller, I get my data. I replaced the $http by a timeout to reproduce the behaviour.

$timeout(function() {
    $rootScope.productList = $scope.productList;
    console.log($rootScope.productList);
}, 500);

http://plnkr.co/edit/7wWxXgq5BARYgm0tYVgf

I tried with a $watch, but I'd take any workaround.


Solution

  • The problem here is that watch() is not a recognized function - what you probably want is $watch(). In other words, you were just missing the $ next to 'watch' in your original code.

    Try this:

    $rootScope.$watch('productList', function(newVal, oldVal) {
      $scope.filters = $rootScope.productList;
      console.log($rootScope.productList);
    })