Can someone please clarify what the lifecycle of an AngularJS controller is?
- Is a controller a singleton, or created / destroyed on demand?
- If the latter, what triggers the creation / destruction of the controller?
Consider the below example:
var demoApp = angular.module('demo')
.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/home', {templateUrl: '/home.html', controller: 'HomeCtrl'})
.when("https://stackoverflow.com/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});
});
eg:
In the above example, when I navigate to /users/1
,user 1 is loaded, and set to the $scope
.
Then, when I navigate to /users/2
, user 2 is loaded. Is the same instance of UserEditorCtrl
reused, or is a new instance created?
- If it’s a new instance, what triggers the destruction of the first instance?
- If it’s reused, how does this work? (ie., the method to load the data appears to run on creation of the controller)