$scope.$watch(function(){return self.user}, function (newVal, oldVal, scope){
if (self.user) {
getNotificationCount();
}
});
var getNotificationCount = function(){
console.log("called your function");
}
In the current code snippet the problem lies in the way you are trying to declare a function getNotificationCount, you are declaring a function by assignment. Therefore, execution order sets in a way that first $scope.$watch code block will execute and once it is completed, variable declaration getNotificationCount will execute.
But if you define the you getNotificationCount method as a function expression, then
function getNotificationCount() {
console.log('calling your function')
}
you will not get an error. All the function expression in a scope are evaluated before an execution order is set in place.
It doesn't matter whether you define a function this way whether before or after $scope.$watch().
So, when you define a method in this manner, compiler will first evaluate all the method definitions, then when the execution order reaches the $scope.$watch statement, it will already have the function definition to getNotificationCount to invoke.
In your case the compiler doesn't even know before hand what exists on the right hand side of the var getNotificationCount until it reaches to execute it after $scope.$watch executes( in case this even completes without throwing an error)