0

I am having an issue where I have a function like this...

$rootScope.canNavigate = function(stateName) {
  return !stateName || Authentication.canNavigate.call(Authentication, $state.get(stateName));
};

The problem is this function gets called continuously. The stack trace is different every time but has one thing in common, it is always coming from $apply. I have commented out all of the watches that are using this function and it is still happening. Does anyone know why this is happening? I cannot seem to reproduce in a plunker.

Jackie
  • 21,969
  • 32
  • 147
  • 289

2 Answers2

0

If there is a call of this function on any of your html, this function will be called every time angular executes a digest cycle in order to do dirty checking (See this question on SO in order to get some kind of reference about this)... except you use the bind once expression (See syntax on this article and this on SO)

It is called from $apply because

$apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). Because we are calling into the angular framework we need to perform proper scope life cycle of exception handling, executing watches.

but $apply is (also) used by the own framework for making a digest cycle.

Community
  • 1
  • 1
lealceldeiro
  • 14,342
  • 6
  • 49
  • 80
0

Asiel probably has the right answer depending on your situation, but as to how to prevent it, you can either use the bind once expression as Asiel suggests or, if that's not possible for some reason, you could also save the results so you're not calling that service every time.

var canNavigateCache = {};

$rootScope.canNavigate = function(stateName) {
  return !stateName
    || canNavigateCache[stateName]
    || canNavigateCache[stateName] = 
         Authentication.canNavigate.call(Authentication, $state.get(stateName));
};

This also gives you the ability to clear the cache if you need to by just resetting the cache object (canNavigateCache = {})

adam0101
  • 29,096
  • 21
  • 96
  • 174