In a project I'm working on we've got a variable on the $rootScope called events. I can access this in my controllers using $rootScope.events after injecting it to my controller.
It can take some time before the service sets the events on the $rootScope variable. Now am I adding a new functionality that needs the ID from the first event of the variable. The problem is, it's getting called before $rootScope.events is set. I can't figure out how to call the method in my controller after the $rootscope.events is set. I have used $watch before, how ever, it doesn't seem to work on this variable. The code I tried:
$scope.$watch('$rootScope.events', function() {
if ($rootScope.events.length > 0) {
getDetails(); // function I want to call after $rootscope.events is set
$log.debug($rootScope.events); // debugging line
}
});
I added the $rootScope.events.length > 0 to avoid it's getting in a infinite loop. Not sure if this is necessary. Is there a solution for what I need to add this functionality? Something like this watch? Or have I done something wrong?
I don't think you need more code then I've added to this post as I just inject $scope and $rootScope in my controller, and then $log.debug() should get called with the set variable. Currently it returns an empty variable. If I'm wrong just let me know in the comments.
It's been awhile, but I think you want this:
eventsis a value on$rootscopebut$rootscope.eventsis not a value on$scope.To avoid cluttering
$rootscopewith watches, however, you should probably use:Or simply: