why the local controller gets called twice and how to avoid

334 views
Skip to first unread message

Rahul Upakare

unread,
Nov 14, 2013, 2:18:26 PM11/14/13
to ang...@googlegroups.com
Here is a plunk: http://plnkr.co/edit/yqeXI9?p=preview

The snippet:

<body ng-controller="MainCtrl">
   <div ng-include="'template.html'"></div>
 </body>

and in template.html: 

<div ng-controller="localCtrl">
{{check()}}
</div>

The check function has an alert call, which gets invoked twice. Why?

Thanks,
--
Rahul Upakare

Mark Volkmann

unread,
Nov 14, 2013, 5:55:53 PM11/14/13
to ang...@googlegroups.com
I am also very curious about this. I have run into this many times.
Here is a simplified version of your plunk that demonstrates the same thing:


--
You received this message because you are subscribed to the Google Groups "AngularJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email to angular+u...@googlegroups.com.
To post to this group, send email to ang...@googlegroups.com.
Visit this group at http://groups.google.com/group/angular.
For more options, visit https://groups.google.com/groups/opt_out.



--
R. Mark Volkmann
Object Computing, Inc.

OpenNota

unread,
Nov 14, 2013, 6:21:59 PM11/14/13
to ang...@googlegroups.com
This is how $digest loop works. Angular adds a watch for the expression in curly brackets, then $digest loop runs at least 2 times, to guarantee that none of expressions values were changed. It means that your expression will be evaluated (and so the function will be called) at least twice.  It also will be called whenever angular suspects that the scope could be modified. Try to click the button:

http://plnkr.co/edit/hcrA6uptxDLb21jHnHGm?p=preview

$digest()
Processes all of the watchers of the current scope and its children. Because a watcher's listener can change the model, the $digest() keeps calling the watchers until no more listeners are firing. This means that it is possible to get into an infinite loop. This function will throw 'Maximum iteration limit exceeded.' if the number of iterations exceeds 10.
 
Reply all
Reply to author
Forward
0 new messages