I'm trying to build a header directive that:
- If logged in, should display the username and a Log Out button
- If logged out, should hide the above-mentioned things
I'm using a custom login service that captures this information, and broadcasts the events login and logout. I'm successfully listening to these events in both the header's controller and directive.
How can I reload the directive on these events?
loginService.js:
angular.module("app")
.service("loginService", ["$http", "$rootScope", function ($http, $rootScope) {
var loggedIn = false,
_username = "";
this.logIn = function (username, password) {
// do some validation...
loggedIn = ...validation was successful;
_username = username;
if (loggedIn) {
$rootScope.$broadcast("login");
}
};
this.getUsername = function () {
return _username;
};
this.isLoggedIn = function () {
return loggedIn;
};
this.logOut = function () {
loggedIn = false;
$rootScope.$broadcast("logout");
};
}]);
headerController.js
angular.module("app")
.controller("headerController", ["loginService", "$rootScope", "$location", function (loginService, $rootScope, $location) {
this.isLoggedIn = loginService.isLoggedIn();
this.username = "";
$rootScope.$on("login", function (event) {
this.isLoggedIn = loginService.isLoggedIn();
this.username = loginService.getUsername();
});
this.logOut = function () {
loginService.logOut();
this.isLoggedIn = loginService.isLoggedIn();
this.username = "";
$location.path("/login"); // redirecting
};
}]);
header.html:
<header ng-controller="headerController as header">
<span ng-if="header.isLoggedIn">{{header.username}} <button ng-click="header.logOut()">Log Out</button></span>
</header>
headerDirective.js
angular.module("app")
.directive("header", function () {
return {
restrict: "A",
transclude: false,
templateUrl: "app/header/header.html",
controller: "headerController",
link: function (scope, element, attrs) {
scope.$on("login", function (event) {
// show the ng-if in header.html??
});
scope.$on("logout", function (event) {
// hide the ng-if in header.html??
});
}
};
});
I'm using this as <div header></div>.
restrict: "E"instead ofrestrict: "A"since you're using it as an element?headerelement exists in HTML5, and it would be better to avoid confusing yourself to name your element something different. It's fine if it's an attribute, but it should be named differently.<div header></div>, but renaming for clarity and using this as an element are good ideas thx.