Can someone please clarify what the lifecycle of an AngularJS controller is?(有人可以澄清一下AngularJS控制器的生命周期是什么吗?)
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('/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
.(在上面的示例中,当我导航到/users/1
,加载了用户1,并设置为$scope
。)
Then, when I navigate to /users/2
, user 2 is loaded.(然后,当我导航到/users/2
,加载用户2。) Is the same instance of UserEditorCtrl
reused, or is a new instance created?(是否重用UserEditorCtrl
的相同实例,或者是否创建了新实例?)
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)((即,加载数据的方法似乎在创建控制器时运行))
ask by Marty Pitt translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…