scenario
Consider the following scenario:At the right of top navbar of the application screen, user should see his username and "sign out" link while he is loggedin:
loggedin view
and when he is not logged in - "signin" and "singnup" links should be displayed.
not-loggedin view
directive
Lets build simple directive user-menu which will be placed into top navbar of our page:
<ul>
<user-menu></user-menu>
</ul>
usermenu.js
angular.module("myApp")
.directive('userMenu', function () {
return {
restrict: 'E',
templateUrl: 'usermenuTpl.html',
controller: function ($scope, userSvc) {
if (userSvc.isAuthenticated()) {
$scope.profile = userSvc.getProfile();
}
}
}
})
userMenuTpl.html
<ul class="nav navbar-nav navbar-right" ng-if="profile">
<li>
<a href="/profile"><i class="glyphicon glyphicon-user">
</i> {{profile.username}}
</a>
</li>
<li style="border-left:1px solid #fff">
<a href="/link-to-logout">Sign out</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right" ng-if="!profile">
<li>
<a href ng-click="open()">Sign in</a>
</li>
<li>
<a style="border-left:1px solid #fff" href="/link-to-login">Sign Up</a>
</li>
</ul>
All things are simple - directive consists from 2 templates, and display each wether "profile" property is set or not.
"Profile" property will came from some User service (which usually should access to DB, but for being simple lets fake it)
userSvc.js
angular.module("myApp")
.factory('userSvc', function () {
return {
isAuthenticated: function () {
return true;
},
getProfile: function () {
return {username: 'Shlomo'};
}
}
})
for testing manually lets see what happens when we changing code of isAuthenticated method so it returns false. Yes - we see signin & signup links.
So far so good
Hope you have fun reading
Part 2