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

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>

Related

How can I develop a popup that open on a button click (Angularjs)

Any one can refer me a link or a demo of code for developing a popup using angularjs.
I have tried the following code but it's not working.
var myApp = angular.module('myApp', ['ngRoute', 'ngMap', 'ui.bootstrap']);
myApp.config(function($routeProvider, $locationProvider) {
$locationProvider.hashPrefix('');
$routeProvider
.when("/", {
templateUrl: "views/home.php",
controller: 'PopupDemoCont'
})
.when("/profile.php", {
templateUrl: "views/profile.php"
})
.otherwise({
redirectTo: "/"
});
});
myApp.controller("ImageController", ["$scope", function($scope) {
$scope.logoimage = "images/logo.png";
$scope.bgtextimage = "images/bgtextimage.png";
}]);
myApp.controller("PopupDemoCont", ["$scope", "$modal", function($scope, $modal) {
$scope.open = function() {
console.log('opening pop up');
var modalInstance = $modal.open({
templateUrl: 'views/popup.php',
controller: 'PopupCont'
});
};
}]);
myApp.controller("PopupCont", ["$scope", "$modalInstance", function($scope, $modalInstance) {
$scope.close = function() {
$modalInstance.dismiss('cancel');
};
}]);
In bellow html, I set ng-controller but it isn't working.
<div class="book_div">
<div class="book_content">
<p id="book-text">Facing Immigration
<br> Problems?
</p>
<p>Helpful Guid To Navigate Your Case</p>
<div class="hidden-sm hidden-xs"><img ng-src="{}" class="center-block img-responsive">
</div>
<a class="submit-button book_btn" ng-click="open()">Free download</a>
</div>
</div>
It is giving the Error:
[$injector:unpr].
You can use uibModalinstance.
On button click call the function open.
code for open function:
$scope.open = function(uuid,name){
var instance = $uibModal.open({
animation: $scope.animationsEnabled,
templateUrl: 'common/common/partials/delete-
confirm.tpl.html',
controller: function ($uibModalInstance,
$scope) {
$scope.name = Name;
$scope.icon = "fa-cogs";
$scope.description = "Yo have opened uib
Popup"
$scope.delete = function () {
$uibModalInstance.close($scope.deleteValue);
};
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
};
}
});
}
I have used this code for deleting my record. You can use in your way, if you want to take response of Popup you can use:
instance.result.then(function (option) {
// Your code here
}, function () {
console.log('Modal dismissed at: ' + new Date());
});
HTML template will be like:
<div class="modal-header gray_background">
<h4><b>Permanently Delete - <i class="fa {{icon}} folderIcon" aria-hidden="true"></i> {{name}} </b></h4>
</div>
<div class="modal-body">
<span data-ng-bind-html="description"></span>
<center style="margin-top: 10px;">
<div>Type "delete" to confirm
<input type="text" class="input" ng-model="deleteValue" required />
</div>
</center>
</div>
<div class="modal-footer gray_background">
<button class="btn btn-default" type="button" ng-click="cancel()">Cancel</button>
<button class="btn btn-danger" type="button" ng-click="delete()">Delete</button>
</div>
Hope this would be helpful, if you have any further query you can ask.
Thanks!

Displaying username after login with angular

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.

function is not called with anchor tag in angular

Unable to call logout function inside login controller. I have simple login and logout functionality using ui-router.
I am able to login and route to other page but I am not able to call logout function. I have tried all the possible solutions such as using:
<li><a href ng-click="$event.preventDefault();logout()">Logout</a></li> //only href
<li>Logout</li> //empty href
<li><a href ng-click="$event.preventDefault();logout()">Logout</a></li> //href with event
button class="btn" ng-click="logout()">Logout</button> //also button type
However, none of the above fired the logout function. I guess something wrong with scope or stateprovider.
Stateprovider:
myApp.config(function ($stateProvider, $urlRouterProvider) {
// default route
$urlRouterProvider.otherwise("/Home");
// ui router states
$stateProvider
.state('Home', {
url: "/Home",
views: {
content: {
templateUrl: 'views/HomePage.html',
controller: function ($scope) {
}
}
}
})
.state('LoggedIn', {
url: "/LoggedIn",
views: {
'content': {
templateUrl: 'views/LoggedIn.html',
controller: function ($scope) {
}
}
}
});
});
Login controller:
myApp.controller('loginController', ['$scope', '$http', 'jwtHelper', '$localStorage', '$sessionStorage', '$state', '$window', function ($scope, $http, jwtHelper, $localStorage, $sessionStorage, $state, $window)
{
$scope.loginForm = function (email, password) {
if (email !== undefined && password !== undefined) {
$http.post('rs/loginResource/login', {email: email, password: password})
.then(function (data) {
$localStorage.token = data.token;
$state.go('LoggedIn');
console.log(data.data.token);
})
.catch(function (error) {
console.log(error);
});
}
$scope.logout = function () {
alert("logout called"); //it is not firing the alert here
delete $localStorage.token;
$state.go('Home');
};
};
}]);
Index html:
<boyd>
<div id="wrap">
<div ui-view="content"></div>
</div>
</body>
Main html:
<div ng-controller="loginController">
<form class="form" method="post" ng-submit="loginForm(email, password)">
<div class="form-group">
<label class="sr-only">Email address</label>
<input type="email" ng-model="email" required>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" ng-model="password">
</div>
<div class="form-group">
<button type="submit">Sign in</button>
</div>
</form>
</div>
LoggedIn html:
<div ng-app="myApp">
<nav>
<div class="container">
<div ng-controller="loginController">
<ul>
<li><a href ng-click="logout()">Logout</a></li>
</ul>
</div>
</div>
</nav>
<h2>Logged In....</h2>
</div>
The logout function seems to be inside the loginForm function

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">
...

Angular JS routing issue when using Service

I have a situation, I want to redirect user to next page if login is successful.
Else it should stay on login page.
Here is my code where I have set the routing and routeChangeStart listener.
function () {
"use strict";
angular.module("app", ["ngRoute", "ngAnimate", "ui.bootstrap", "easypiechart", "mgo-angular-wizard", "textAngular", "ui.tree", "ngMap", "app.ui.ctrls", "app.ui.directives", "app.ui.services", "app.controllers", "app.directives", "app.form.validation", "app.ui.form.ctrls", "app.ui.form.directives", "app.tables", "app.map", "app.task", "app.localization", "app.chart.ctrls", "app.chart.directives", "app.tekcapital.authModule"]).config(["$routeProvider", function ($routeProvider) {
return $routeProvider.when("/", {
templateUrl: "web-view/dashboard.html"
}).when("/dashboard", {
templateUrl: "web-view/dashboard.html"
}).when("/pages/features", {
templateUrl: "web-view/pages/features.html"
}).when("/pages/login", {
templateUrl: "web-view/pages/login.html"
}).when("/pages/login_fail", {
templateUrl: "web-view/pages/login_fail.html"
}).when("/pages/create_idn_1", {
templateUrl: "web-view/pages/create_idn_1.html"
}).when("/pages/create_idn_2", {
templateUrl: "web-view/pages/create_idn_2.html"
}).when("/pages/create_idn_3", {
templateUrl: "web-view/pages/create_idn_3.html"
}).when("/pages/create_idn_4", {
templateUrl: "web-view/pages/create_idn_4.html"
}).when("/pages/create_idn_5", {
templateUrl: "web-view/pages/create_idn_5.html"
}).when("/pages/create_idn_6", {
templateUrl: "web-view/pages/create_idn_6.html"
}).when("/pages/create_idn_7", {
templateUrl: "web-view/pages/create_idn_7.html"
}).when("/pages/signin", {
templateUrl: "web-view/pages/signin.html"
}).when("/pages/signup", {
templateUrl: "web-view/pages/signup.html"
}).when("/pages/lock-screen", {
templateUrl: "web-view/pages/lock-screen.html"
}).when("/pages/profile", {
templateUrl: "web-view/pages/profile.html"
}).when("/404", {
templateUrl: "web-view/pages/404.html"
}).when("/pages/500", {
templateUrl: "web-view/pages/500.html"
}).when("/pages/blank", {
templateUrl: "web-view/pages/blank.html"
}).when("/pages/invoice", {
templateUrl: "web-view/pages/invoice.html"
}).when("/pages/services", {
templateUrl: "web-view/pages/services.html"
}).when("/pages/about", {
templateUrl: "web-view/pages/about.html"
}).when("/pages/contact", {
templateUrl: "web-view/pages/contact.html"
}).when("/tasks", {
templateUrl: "web-view/tasks/tasks.html"
}).otherwise({
redirectTo: "/404"
})
}]).run(function($rootScope,$location,UserService){
$rootScope.$on("$routeChangeStart", function(event,next, current){
if(UserService.isLogged == null || !UserService.isLogged){
if(next.templateUrl === "web-view/pages/login.html"){
}else{
$location.path("/pages/login");
}
}
});
});
}.call(this)
Below is my login page
<div class="page page-general" ng-controller="AuthController">
<div class="signin-header">
<div class="container text-center">
<section class="logo">
<span class="logo-icon "><img src="images/assets/logo_RS.png" width="262" height="48" alt="tekcapital" /></span>
</section>
</div>
</div>
<div class="signup-body">
<div class="container">
<div class="form-container">
<section class="row signin-social text-center bg-info" style="padding: 12px 0">
Sign In To Tekcapital IDN
</section>
<span class="line-thru"></span>
<form class="form-horizontal" name="loginForm" novalidate>
<fieldset>
<div class="form-group">
<div class="input-group input-group-lg" style="width:100%;">
<input type="username" class="form-control" placeholder="username" ng-model="loginForm.userName" required>
</div>
</div>
<div class="form-group">
<div class="input-group input-group-lg" style="width:100%;">
<input type="password" class="form-control" placeholder="password" ng-model="loginForm.password" required>
</div>
</div>
<div>{{loginForm.$valid}}</div>
<div class="form-group">
Login
</div>
</div>
</div>
</div>
</div>
And here is my code for service and controller
function () {
"use strict";
angular.module("app.tekcapital.authModule", []).factory("UserService", [function () {
var sdo = {
isLogged: false,
username: ''
};
return sdo;
}]).controller("AuthController", ["$scope", "$http", "UserService", function ($scope, $http, UserService) {
$scope.validUser = "";
$scope.loginForm = {};
$scope.getData = function () {
$http.post("http://localhost:8191/authenticate",{"userName":$scope.loginForm.userName,"password":$scope.loginForm.password})
.success(function(dataFromServer, status, header, config){
console.log("data from server " + dataFromServer);
console.log("User Service " + UserService.isLogged)
if(dataFromServer == "true"){
UserService.isLogged = true;
UserService.username = "Test User Name";
}else{
UserService.isLogged = false;
UserService.username = "";
}
console.log("User Service 2 " + UserService.isLogged)
});
};
}])
}.call(this);
Now the issue is that when I validate for the first time it stays on the login page. And on second successful attempt it redirects to another page.
In case of wrong credentials it is working fine. It stays on login page.
And even when I use $location.path('after/login/page') it moves me to that login page.
But when I open a new tab with "localhost:8191/#/pages/success/ it again takes me to login page.
If I have logged in once then it should not take me to login page.
Need help in this regard.
Regards

Categories