1

Are parts of Angular like controllers, services, templates, etc destroyed and recreated when you move from page to page?

Or are they created when needed and never destroyed?

Or are they all initialized when the application is loaded the first time?

What is the lifecycle of an Angular app and its parts like?

Derek
  • 11,980
  • 26
  • 103
  • 162
  • 1
    If you do a full page reload, then yes - everything is "destroyed" and reloaded/recreated. Just like a "normal" web page does. If you use partial views (the ng-view directive) and the Angular routing mechanism, then things are different. Services are singletons which are created and kept in memory and they "survive" routing changes. More info here: http://stackoverflow.com/questions/16094940/what-is-the-lifecycle-of-an-angularjs-controller – HaukurHaf Jun 28 '14 at 22:59
  • 1
    It's very educational to sprinkle some `console.log("this happened!")` statements through your code and watch what is logged. I've done that when I've had similar questions about e.g. the controller lifecycle with routes/ng-view. – Henrik N Jun 29 '14 at 08:41

1 Answers1

1

Defining page here as a single route, and the app as all routes combined.

controllers are instantiated every time they're injected into something, through a route or by using ngController. You'll get a new one every time you visit a page so data you're storing on them will perish between page changes.

services are singletons so are instantiated only the first time and then persist throughout the life of the app, which ends when the site itself is refreshed or the user surfs away. Factories are not instantiated so they too can be used for persistent data.

templates are not instances, they're just html that is parsed against scope variables.

Jorg
  • 7,219
  • 3
  • 44
  • 65