Reputation: 925
I'm learning angular and have a sample login code. This code has a constructor that clears out the credentials when called. My question is: when is the constructor called? Is it once when the code is initialized or every time a method on the controller is called? I might be confusing this with the way my backend dev framework works with DI which runs the constructor for my controllers only once when initialized.
As a followup question, do I need a logout function or will the constructor be good enough?
This is the code I'm looking at currently:
(function () {
'use strict';
angular
.module('app')
.controller('LoginController', LoginController);
LoginController.$inject = ['$rootScope', '$location', 'AuthenticationService', 'FlashService'];
function LoginController($rootScope, $location, AuthenticationService, FlashService) {
var vm = this;
vm.login = login;
(function initController() {
// reset login status
AuthenticationService.ClearCredentials();
})();
function login() {
vm.dataLoading = true;
var promise = AuthenticationService.Login(vm.username, vm.password)
.then(function(userInfo){
AuthenticationService.SetCredentials(userInfo);
$location.path('/');
}, function(failedReason) {
FlashService.Error(failedReason);
vm.dataLoading = false;
});
};
function logout() {
AuthenticationService.ClearCredentials();
$location.path('/login');
};
}
})();
Upvotes: 3
Views: 3381
Reputation: 856
The controller will be called when and ng-controller is found in html document or when a view is changed.
And when a controller is called all functions side it will be initialized but not called.So you may have to call the log out function to logout user.but re rendering the view will logout the user Which I don't think is the case here.(I am assuming it is a single view template)
Here the snippet from angular documentation.. Go through it again. ""In Angular, a Controller is defined by a JavaScript constructor function that is used to augment the Angular Scope.
When a Controller is attached to the DOM via the ng-controller directive, Angular will instantiate a new Controller object, using the specified Controller's constructor function. A new child scope will be created and made available as an injectable parameter to the Controller's constructor function as $scope.
If the controller has been attached using the controller as syntax then the controller instance will be assigned to a property on the new scope.""
Upvotes: 2
Reputation: 7066
It gets called every time a view or directive to which it is attached gets displayed.
Upvotes: 9