Displaying username after login with angular - javascript

I'm playing around with AngularJS and trying to build a very simple app for learning purposes, but i've ran into a problem.
I'm using Kinvey BAAS. So, this is what I'm trying to do:
I have a login.controller.js, which looks like this (skipping the module registration and the config parts...):
`
.controller('LoginController', [
'$scope',
'$location',
'users',
function ($scope, $rootScope, $location, users) {
$scope.login = function login() {
users.login($scope.user)
.then(function (loggedInUser) {
$location.path('/home');
console.log(loggedInUser);
}, function (error) {
console.log(error);
});
}
}
])
The idea is simple. Use a service to log the user in. Then, redirect him to the homepage (/home).
The authentication service looks like this (users.js):
`
.factory('users', [
'$http',
'$q',
'$cookies',
'$location',
'BASE_URL',
'APP_KEY',
'APP_SECRET',
function ($http, $q, $cookies, $location, BASE_URL, APP_KEY, APP_SECRET) {
var user = undefined;
function login(user) {
var deferred = $q.defer();
// Get the user information.
$http.post(BASE_URL + 'user/' + APP_KEY + '/login', {
username: user.username,
password: user.password
})
.then(function (response) {
_preserveUserData(response.data);
deferred.resolve(response);
}, function (error) {
deferred.reject(error);
});
return deferred.promise;
}
function _preserveUserData(data) {
var authToken = data._kmd.authtoken;
$cookies.put('authToken', authToken);
user = data;
}
function isLogged() {
if !! (user || $cookies.get('authToken'));
}
function getLoggedUser() {
var deferred = $q.defer();
if (user) {
deferred.resolve(user);
} else if ($cookies.get('authToken')) {
var authToken = $cookies.get('authToken');
$http.defaults.headers.common.Authorization = 'Kinvey ' + authToken;
$http.get(BASE_URL + 'user/' + APP_KEY + '/_me')
.then(function (response) {
user = response.data;
deferred.resolve(response);
}, function (error) {
deferred.reject(error);
});
} else {
deferred.reject('No logged user.');
}
return deferred.promise;
}
return {
login: login,
isLogged: isLogged,
getLoggedUser: getLoggedUser
};
}
]);
I also have a main controller (main.controller.js). The MainController wraps the whole content with a div (), for binding to the scope some global stuff...like the currently logged user.
`
.controller('MainController', [
'APP_TITLE',
'$scope',
'users',
function (APP_TITLE, $scope, users) {
// A place to store some more-global stuff.
$scope.appTitle = APP_TITLE;
$scope.user = undefined;
if (users.isLogged()) {
users.getLoggedUser()
.then(function (loggedUser) {
$scope.user = loggedUser.data;
}, function (error) {
console.log(error);
});
}
}
])
Now, this is the index.html (where the Main controller and the ng-view are):
<body>
<div ng-controller="MainController" ng-cloak>
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#!/">{{appTitle}}</a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li>Home</li>
<li>Favorites</li>
<li>Users</li>
</ul>
<ul class="nav navbar-nav navbar-right" ng-if="user">
<li class="dropdown">
{{user.username}}<span class="caret"></span>
<ul class="dropdown-menu">
<li>Links</li>
<li>Edit Profile</li>
<li role="separator" class="divider"></li>
<li>Logout</li>
</ul>
</li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
<!--[if lt IE 7]>
<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please upgrade your browser to improve your experience.</p>
<![endif]-->
<div ng-view>
</div>
</div>
And this is the home.html (where the username should be displayed):
<div class="container">
<h2>Hello, <span ng-if="user">{{user.username}}</span></h2>
</div>
The thing is that, when the user is logged, I save a cookie and redirect the logged user...but the MainController doesn't register the logged in user (it never enters the if (users.isLogged()) part). I have to refresh to see the username of the user.
Any guidance on how to solve this problem will be handy. Also code quality and overall code-improvement suggestions will be also highly appreciated.
Thanks in advance!
Borislav.

users should be a service, not a factory... a service will create a single shared instance, a factory is a new instance for each controller.

Related

Change ng-show value in other controller

I'm trying to show and hide a div using ng-show. It's a navbar that I want to show only in some views.
I have a controller which "controls" that div. And in other controller I want to edit this ng-show value in order to hide or show the div (navbar).
I tried different things as using a $rootScope, a timeout, an $apply, a factory... but nothing works.
So I'm asking here if anyone could help me.
(Sorry for my English)
This is my html and js codes (last edit code)
<div id="main">
<!-- AquĆ­ inyectamos las vistas -->
<div ng-controller="appCtrl" ng-show="isLogged" class="navbar navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button>
<a class="navbar-brand" href="#/">Aula Virtual</a> </div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav" style="text-align: right">
<li class="active">Home</li>
<li>Users</li>
<li>Operaciones</li>
<li>About</li>
<li>Contact</li>
</ul>
</div>
</div>
<div class="connect">
<div class="container">
<p>
Aula Virtual para profesorado y alumnos de la universidad
</p>
</div>
</div>
</div>
<div ui-view></div>
</div>
I tried a (ng-show="isLogged==false") too.
The controller of the div:
.controller('appCtrl', function($scope, $rootScope) {
console.log($scope.isLogged); //---> this shows undefined
});
The controller where I want to edit the isLogged value:
cities2.controller('userCtrl',['rootScope', '$scope', '$state','$http','md5', function($rootScope, $scope, $state, $http, md5) {
$rootScope.$apply(function(){
$rootScope.isLogged = true;
});
Thanks for the help!
It's good practice to use services to share data between controllers.
cities2.controller('appCtrl', ['$scope', 'LoggedStatus', function($scope,LoggedStatus) {
$scope.LoggedStatus = LoggedStatus;
}]);
cities2.controller('userCtrl', ['$scope', 'LoggedStatus', function($scope,LoggedStatus) {
$scope.LoggedStatus = LoggedStatus;
}]);
cities2.service('LoggedStatus', function() {
return {
isLogged: false
}
});
Changing the value of $scope.LoggedStatus.isLogged in either controller will change the value in both.
In your appCtrl controller, do $scope.isLogged=0. If you change this value to 1, the block will be visible else it will be hidden.
app.controller('appCtrl', function($scope) {
$scope.isLogged=0;
})
Refer to the plunker below:
https://plnkr.co/edit/d3q3QwA9k5f6ewXbqZ3M?p=preview
Well, finally I found the solution. I put this if can help someone:
I put a .run in the appCtrl where I initialize the ng-show:
.run(function ($rootScope) {
$rootScope.isLogged = false;
});
and now, when I put a true value in the other controller it works, and the navbar appears.
cities2.controller('userCtrl',['$rootScope', '$scope', '$state','$http','md5','$sessionStorage', function($rootScope, $scope, $state, $http, md5, $sessionStorage) {
$rootScope.isLogged=true;
}]);

Unable to change the name of login button using ng-show

I am setting a boolean value to true after user logs in and I want to update the login button status to logout. I tried using ng-show but apparently its not working.
States:
myApp.config(function ($stateProvider, $urlRouterProvider) {
// default route
$urlRouterProvider.otherwise("/Home");
var header = {
templateUrl: 'commonViews/Header.html',
controller: function ($scope) {
}
};
var footer = {
templateUrl: 'commonViews/Footer.html',
controller: function ($scope) {
}
};
// ui router states
$stateProvider
.state('Home', {
url: "/Home",
views: {
header: header,
content: {
templateUrl: 'views/HomePage.html',
controller: function ($scope) {
}
},
footer: footer
}
})
.state('LoggedIn', {
url: "/LoggedIn",
views: {
'header': header,
'content': {
templateUrl: 'views/LoggedIn.html',
controller: function ($scope) {
}
},
'footer': footer
}
});
});
UserService:
myApp.factory('UserService', function ($http, $localStorage, AuthenticationService) {
return {
logIn: function (email, password) {
return $http.post('rs/loginResource/login', {email: email, password: password})
.then(function (data) {
AuthenticationService.isLogged = true;
alert("Authentication loggedIn inside login controller: " + AuthenticationService.isLogged);
return data;
})
.catch(function (error) {
console.log(error);
});
},
logOut: function () {
if (AuthenticationService.isLogged) {
AuthenticationService.isLogged = false;
delete $localStorage.token;
}
}
};
});
myApp.factory('AuthenticationService', function () {
var auth = {
isLogged: false
};
return auth;
});
Login controller:
myApp.controller('loginController', ['$scope', '$http', 'jwtHelper', '$localStorage', '$sessionStorage', '$state', '$window', 'UserService', 'AuthenticationService', function ($scope, $http, jwtHelper, $localStorage, $sessionStorage, $state, $window, UserService, AuthenticationService)
{
$scope.token = "";
$scope.$storage = $localStorage;
$scope.loginForm = function (email, password) {
if (email !== undefined && password !== undefined) {
UserService.logIn(email, password).then(function (response) {
$localStorage.token = response.data.token;
if ($localStorage.token) {
$state.go('LoggedIn');
alert("scope loggedIn inside login controller: " + AuthenticationService.isLogged);
}
}).catch(function (status, data) {
console.log(status);
console.log(data);
});
}
$scope.logout = function logout() {
UserService.logOut().success(function () {
$state.go('/');
}).error(function (status, data) {
console.log(status);
console.log(data);
});
};
};
}]);
index.html:
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head></head>
<body>
<div ui-view="header"></div>
<div ui-view="content"></div>
<div ui-view="footer"></div>
</body>
</html>
Header html:
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<b>Logout</b>
<b>Login</b> <span class="caret"></span>
<ul id="login-dp" class="dropdown-menu">
<!---------------------------------Login Controller Here------------------------------------->
<li>
<div class="row">
<div class="col-md-12">
<form class="form" role="form" method="post" ng-controller="loginController" ng-submit="loginForm(email, password)" accept-charset="UTF-8" id="login-nav">
<div class="form-group">
<label class="sr-only" for="exampleInputEmail2">Email address</label>
<input type="email" class="form-control" ng-model="email" id="exampleInputEmail2" placeholder="Email address" required>
</div>
<div class="form-group">
<label class="sr-only" for="exampleInputPassword2">Password</label>
<input type="password" class="form-control" id="exampleInputPassword2" ng-model="password" placeholder="Password" required>
<div class="help-block text-right">Forget the password ?</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-block">Sign in</button>
</div>
</form>
</div>
</div>
</li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
After user is logged in, it changes the status to logout for split second and then back to login status again. I am not sure what's going wrong?
Add AuthenticationService to the scope of your controller,
$scope.AuthenticationService = AuthenticationService;
and remove $scope from your view/template
<ul class="nav navbar-nav navbar-right" ng-controller="loginController">
<li class="dropdown">
<b>Logout</b>
<b>Login</b> <span class="caret"></span>
</li>
Put an isLoggedIn() function in your header controller:
myApp.config(function ($stateProvider, $urlRouterProvider) {
// default route
$urlRouterProvider.otherwise("/Home");
var header = {
templateUrl: 'commonViews/Header.html',
controller: function ($scope, AuthenticationService) {
$scope.isLoggedIn = function() {
return AuthenticationService.isLogged;
});
}
};
var footer = {
templateUrl: 'commonViews/Footer.html',
controller: function ($scope) {
}
};
// ui router states
And in your header HTML use that function:
<a href="#" class="dropdown-toggle" data-toggle="dropdown"
ng-show="isLoggedIn()" ng-click="logout()"><b>Logout</b>
</a>
<a href="#" class="dropdown-toggle" data-toggle="dropdown"
ng-show="!isLoggedIn()">
<b>Login</b> <span class="caret"></span>
</a>
UPDATE
Your login controller's scope is a child of the header controller's scope. Your ng-show directives are not in your login controller's scope. By putting functions that query the AuthenticationService.isLogged state in the correct scope, the ng-show directives should work properly.
There are 2 issues in your code
AuthenticationService.isLogged
is not updated after successful login with UserService
You don't need to have $scope in your templates as any Angular expression that you pass in your HTML template will be resolved against the current scope.
I would suggest not to expose your services onto your view layer. Just add a property isLoggedIn on your scope which will determine whether to show Login or Logout buttons.
myApp.controller('loginController', ['$scope', '$http', 'jwtHelper', '$localStorage', '$sessionStorage', '$state', '$window', 'UserService', 'AuthenticationService', function ($scope, $http, jwtHelper, $localStorage, $sessionStorage, $state, $window, UserService, AuthenticationService)
{
$scope.token = "";
$scope.$storage = $localStorage;
// new property to hold login status
$scope.isLoggedIn = false;
$scope.loginForm = function (email, password) {
if (email !== undefined && password !== undefined) {
UserService.logIn(email, password).then(function (response) {
$localStorage.token = response.data.token;
if ($localStorage.token) {
// cache the login status for use in other controllers
AuthenticationService.isLogged = true;
// update the scope for use in templates
$scope.isLoggedIn = true;
$state.go('LoggedIn');
}
}).catch(function (status, data) {
console.log(status);
console.log(data);
});
}
$scope.logout = function logout() {
UserService.logOut().success(function () {
// cache the login status for use in other controllers
AuthenticationService.isLogged = false;
// update scope for use in templates
$scope.isLoggedIn = false;
$state.go('/');
}).error(function (status, data) {
console.log(status);
console.log(data);
});
};
};
}]);
With this, in your templates, you can just check for isLoggedIn like below
<ul class="nav navbar-nav navbar-right" ng-controller="loginController">
<li class="dropdown">
<a href="#" class="dropdown-toggle"
data-toggle="dropdown"
ng-show="isLoggedIn"
ng-click="logout()">
<b>Logout</b></a>
<a href="#" class="dropdown-toggle"
data-toggle="dropdown"
ng-show="!isLoggedIn">
<b>Login</b> <span class="caret"></span>
</a>
</li>
</ul>

AngularJs Error - Uncaught Error: [$injector:unpr]

I am new to AngularJs, i have seen enough posts for a similar question but haven't found solution for my problem. I am using Angular 1.4.5
app.js (Omitted additional code like Routes and interceptors):
'use strict';
var app = angular.module('app', ['ngRoute', 'authControllers', 'authServices']);
var authControllers = angular.module('authControllers', []);
var authServices = angular.module('authServices', []);
authControllers.js:
authControllers.controller('authCtrl', ['$scope', '$location', '$window', 'UserService', 'AuthenticationService',
function authCtrl($scope, $location, $window, UserService, AuthenticationService) {
//Admin User Controller (login, logout)
$scope.logIn = function logIn(username, password) {
if (username !== undefined && password !== undefined) {
UserService.logIn(username, password).success(function(data) {
AuthenticationService.isLogged = true;
$window.sessionStorage.token = data.token;
$location.path("/");
}).error(function(status, data) {
console.log(status);
console.log(data);
});
}
}
$scope.logout = function logout() {
if (AuthenticationService.isLogged) {
AuthenticationService.isLogged = false;
delete $window.sessionStorage.token;
$location.path("/");
}
}
}
]);
authServices.js:
authServices.factory('AuthenticationService',function() {
var auth = {
isLogged: false
}
return auth;
});
Index.html:
<body ng-app="app">
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation" data-ng-controller="authCtrl">
<!-- data-ng-controller="authCtrl" -->
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Angular Restful Auth</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a ng-href="#/">Home</a></li>
<li data-ng-show="token"><a ng-href="#/me">Me</a></li>
<li data-ng-hide="token"><a ng-href="#/signin">Signin</a></li>
<li data-ng-hide="token"><a ng-href="#/signup">Signup</a></li>
<li data-ng-show="token"><a ng-click="logout()">Logout</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
<div class="container" ng-view="">
</div> <!-- /container -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.1/angular-route.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="/js/app.js"></script>
<script src="/js/authentication/authControllers.js"></script>
<script src="/js/authentication/authServices.js"></script>
</body>
Getting
Uncaught Error: [$injector:unpr]
http://errors.angularjs.org/1.4.5/$injector/unpr?p0=AuthenticationServiceProvider%20%3C-%20AuthenticationService
Please let me know what's the mistake i am doing.
Noting down answer as discussed in comments:
The problem was not including the modular js files in index.html
Example:
<script src="/js/authControllers.js"></script>
<script src="/js/authServices.js"></script>

How can I change the menu content after user log in

I have a menu bar defined in the "HomeController" with a login button.
My login form is a ui-bootstrap modal whose controller is "LoginController".
After successfully log in, user is directed to another state. But I also want the "Login" button to hide and show the current user's email.
I think I should use either localstorage or cookies to store the current user information. the localstorage data never expires so I think cookies is better?
So what should I do in my "LoginController" and "MainController"?
Can I use the $emit and $on?
I'm new to angular. Any suggestions would be appreciated.
.state('home', {
url: '/home',
templateUrl: 'template/partial-home.html',
controller:'mainController'
})
.state('login', {
url: '/login',
parent:'home',
onEnter:['$stateParams','$state','$modal','$resource',function($stateParams,$state, $modal, $resource){
$modal.open({
animation: true,
size:'',
templateUrl: 'login/login.html',
controller:'loginController'
}).result.then(function(){
console.log('promise resolved success');
$state.go('admin-dashboard',{});
},function(){
console.log('promise rejected fail');
}).finally(function(){
console.log('promise finally');
//$state.go('home',{});
});
}]
})
.controller('loginController',function($scope,$http,$timeout,AuthToken,$window){
$scope.badCreds = false;
$scope.cancel = function() {
$scope.$dismiss();
};
$scope.login = function() {
console.log($scope.credential);
$http.post('/authenticate',$scope.credential).then(function success(response){
console.log(response.data.token);
AuthToken.setToken(response.data.token);
$scope.currentuser = response.data.user;
$scope.alreadyLoggedIn = true;
console.log('success', 'Hey there!', 'Welcome ' + $scope.currentuser.email + '!');
$scope.$close();
},function error(response){
$scope.message='Problem logging in! Sorry!';
});
};
$scope.logout = function(){
AuthToken.clearToken();
$scope.currentuser = null;
//showAlert('info','Goodbye!','Have a great day!');
};
<body ng-controller="mainController">
<header>
<div class="nav navbar-default navbar-fixed-top" role="navigation">
<div class = "container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Westlake Pioneers</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li><a ui-sref="home" ui-sref-active="active"><i class="fa fa-home"></i>Home</a></li>
<li><a ui-sref="team" ui-sref-active="active"><i class="fa fa-shield"></i>Our Team</a></li>
<li><a ui-sref="blogs" ui-sref-active="active"><i class="fa fa-book"></i>Blogs</a></li>
<li><a ui-sref="projects" ui-sref-active="active"><i class="fa fa-wrench"></i>Projects</a></li>
<li><a ui-sref="contact" ui-sref-active="active"><i class="fa fa-comment"></i> Contact</a></li>
<li><a ng-hide="$rootScope.currentuser" ui-sref="login" ui-sref-active="active"><i class="fa fa-sign-in"></i></i>Login</a></li>
<li>{{currentuser.email}}</li>
</ul>
</div>
</div>
</div>
</header>
<div id="main">
<div class="page {{pageClass}}" ui-view>
</div>
</div>
To pass a parameter into a view when using ui-router do the following:
Add "params" field in your 'home' route definition with an object that will hold the user name ($stateProvider API):
.state('home', {
url: '/home',
templateUrl: 'template/partial-home.html',
controller:'mainController',
params : { userName: null }
})
When closing modal, pass the user name of logged in user back to source (add $uibModalInstance as dependency to login controller, what's $scope.$close()?):
$uibModalInstance.close(response.data.user);
Accept the username in your modal declaration:
.result.then(function (loggedInUserName)
Call $state.go and pass the username to the view:
$state.go('admin-dashboard',{userName:loggedInUserName});
Finally inject $stateParams to the controller that handles 'admin-dashboard' view and access it using $stateParams.userName
Alternatively, if you would like to make username available to the whole application, you can just store it in the $rootScope(dirty) or make an angular service (better).
Good luck!

angularjs ng-show: show menu after successful login

I'm trying to show the navigation bar once the user logs in successfully. but the navigation-bar is still hidden even after the user logs in.
here is a part of the index.html
<header id="Header1" data-ng-controller="navigationController">
<!-- Navigation bar -->
<nav class="navbar navbar-inverse" id="nav1" ng-hide="isConnected">
<div class="collapse navbar-collapse">
<ul id="Ul1" class="nav navbar-nav" style="color: white; font-weight: bolder; font-family: Arial; border-radius: 5px;">
<!-- <li class="nav navbar-brand" id="Li1" style="padding: 0px 0px 0px 0px;">
<img src="favicon.ico" height="20" width="20" />
</li>-->
<li id="Li2" data-ng-class="{'active':isActive('/home')}">
<a data-original-title="Home page." class="disable-click" href="#/home">Home</a>
</li>
<li data-ng-class="{'active':isActive('/demo')}">
<a data-original-title="Demonstration page." class="disable-click" href="#/demo">Demonstration</a>
</li>
</ul>
</div>
</nav>
</header>
the controller navigationController.js is
'use strict';
app.controller('navigationController',
function ($scope, $location, $rootScope, AuthenticationService) {
debugger;
$scope.isActive = function (path) {
return $location.path().substr(0, path.length) == path;
};
$scope.isConnected = !($rootScope.globals.currentUser);
console.log($scope.isConnected);
});
i store the current user in this service
service.SetCredentials = function (username, password) {
var authdata = Base64.encode(username + ':' + password);
$rootScope.globals = {
currentUser: {
username: username,
authdata: authdata
}
};
$http.defaults.headers.common['Authorization'] = 'Basic ' + authdata;
$cookieStore.put('globals', $rootScope.globals);
};
the binding is not working after the login, except when i refresh the menu is shown (when the cookie has became full). any solution please
Your isConnected property is only evaluated once when the controller is instantiated. When the user logs in there is nothing to re-evaluate isConnected
You could set up a watch like this to have it re-evaluate:
'use strict';
app.controller('navigationController',
function ($scope, $location, $rootScope, AuthenticationService) {
debugger;
$scope.isActive = function (path) {
return $location.path().substr(0, path.length) == path;
};
$rootScope.$watch('globals', function(newVal, oldVal) {
$scope.isConnected = !($rootScope.globals.currentUser);
}, true);
});
note it might be possible you can add the watch directly to $scope instead of $rootScope as the globals property should be inherited prototypically, though I haven't tested this to verify
Try this
'use strict';
app.controller('navigationController',
function ($scope, $location, $rootScope, AuthenticationService) {
...
$scope.isConnected = function() {
return !($rootScope.globals.currentUser);
};
});
And do not change ng-hide value to ng-hide="isConnected()", keep it as ng-hide="isConnected"
<nav class="navbar navbar-inverse" id="nav1" ng-hide="isConnected">
...

Categories