title: What is the lifecycle of an AngularJS Controller?
body: <p>Can someone please clarify what the lifecycle of an AngularJS controller is?</p>
  
  <ul>
  <li>Is a controller a singleton, or created / destroyed on demand?</li>
  <li>If the latter, what triggers the creation / destruction of the controller?</li>
  </ul>
  
  <p>Consider the below example:</p>
  
  <pre><code>var demoApp = angular.module('demo')
    .config(function($routeProvider, $locationProvider) {
      $routeProvider
        .when('/home', {templateUrl: '/home.html', controller: 'HomeCtrl'})
        .when('/users',{templateUrl: '/users.html', controller: 'UsersCtrl'})
        .when('/users/:userId', {templateUrl: '/userEditor.html', controller: 'UserEditorCtrl'});
    });
  
  demoApp.controller('UserEditorCtrl', function($scope, $routeParams, UserResource) {
    $scope.user = UserResource.get({id: $routeParams.userId});
  });
  </code></pre>
  
  <p>eg:</p>
  
  <p>In the above example, when I navigate to <code>/users/1</code>,user 1 is loaded, and set to the <code>$scope</code>.</p>
  
  <p>Then, when I navigate to <code>/users/2</code>, user 2 is loaded.  Is the same instance of <code>UserEditorCtrl</code> reused, or is a new instance created?</p>
  
  <ul>
  <li>If it's a new instance, what triggers the destruction of the first instance?</li>
  <li>If it's reused, how does this work?  (ie., the method to load the data appears to run on creation of the controller)</li>
  </ul>