I am currently developing an application using Angular 1 and Typescript. Here is the code snippet for my Login Controller:
module TheHub {
/**
* Controller for the login page.
*/
export class LoginController {
static $inject = ['$http', '$rootScope', '$location'];
constructor(private $http: ng.IHttpService, private $rootScope, private $location: ng.ILocationService) {
}
/**
* Function to validate user login credentials
*/
login(user: {}) {
this.$http.post('/login', user).then((value: ng.IHttpPromiseCallbackArg<{}>) => {
this.$rootScope.auth = { isAuthenticated: true, isAuthenticationChecked: true };
this.$location.url('/');
}, (error: any) => {
this.$rootScope.auth = { isAuthenticated: false, isAuthenticationChecked: true };
});
}
}
angular.module('TheHub').controller('LoginController', LoginController);
}
In my application structure, "App" serves as the main controller with "LoginController" nested underneath it. Despite attempting to update $rootScope in order to refresh the view linked to App after a successful login process, no changes appear to take effect. Looking for solutions, I came across this helpful post on Stack Overflow:
Define and Access $rootScope with controller as syntax
The suggestion mentioned involves creating a service to abstract authentication information, which I see the value in. However, how would two-way data binding be managed effectively? For instance, I aim to display a menu in the App controller's view only when the Login Controller successfully completes the login operation.
Update
App Controller:
module TheHub {
/**
* Main controller.
*/
export class AppController {
static $inject = ['$mdSidenav', '$rootScope'];
constructor(private $mdSidenav: angular.material.ISidenavService, private $rootScope) {
}
/**
* Handler for toggling left menu visibility.
*/
openLeftMenu = () => {
this.$mdSidenav('left').toggle();
}
}
angular.module('TheHub').controller('AppController', AppController);
}
View:
<div id="sideNavContainer" ng-controller="AppController as ctrl" layout="column" ng-cloak layout-fill>
<md-toolbar flex="none">
<div class="md-toolbar-tools">
<md-button class="md-icon-button" aria-label="Settings" hide-gt-md ng-click="ctrl.openLeftMenu()">
<i class="material-icons">menu</i>
</md-button>
The Hub
<span flex></span>
</div>
</md-toolbar>
<md-content flex layout="row">
<md-sidenav ng-show="ctrl.auth.isAuthenticated" class="md-sidenav-left" md-component-id="left" md-is-locked-open="$mdMedia('gt-md')" md-disable-backdrop md-whiteframe="4" flex="none">
<md-content layout-padding>
</md-content>
</md-sidenav>
<div ng-view flex="grow"></div>
</md-content>
</div>