how to stay in current page after refreshing the page in angularjs - html

I am new to angularjs and I have created a login page.
Once I logined it will redirect to my home page. when i click on refresh button it is not staying in current page it is going to login page.
Please can anyone help me.
Thanks in advance.
The below is my code i wrote
login.view.html
<div class="page-wrapper">
<div class="main-wrapper bgm">
<div class="main">
<div class= "document-title"></div>
<div class="container">
<div class=" row">
<div class="col-md-4 col-md-offset-8">
<div class="panel panel-default">
<div class="panel-heading"><div class="logo text-center"><strong>Login</strong></div></div>
<div class="panel-body">
<div role="tabpanel" class="tab-pane active" id="personal">
<div class="row">
<div class="col-sm-12">
<form name="form" ng-submit="vm.login()" role="form">
<div class="form-group" ng-class="{ 'has-error': form.username.$dirty && form.username.$error.required }">
<label for="username">Email/UserName</label>
<input type="text" placeholder="Email/UserName" name="username" id="username" class="form-control" ng-model="vm.username" required />
<span ng-show="form.username.$dirty && form.username.$error.required" class="help-block">Email or username required</span>
</div>
<div class="form-group" ng-class="{ 'has-error': form.password.$dirty && form.password.$error.required }">
<label for="password">Password</label>
<input type="password" name="password" id="password" class="form-control" placeholder="password" ng-model="vm.password" required />
<span ng-show="form.password.$dirty && form.password.$error.required" class="help-block">Password required</span>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-9">
<div class="checkbox"><label class=""><input type="checkbox" class="">Remember me</label></div>
</div>
</div>
<div class="form-actions">
<div class="col-sm-offset-3 col-sm-9">
<button type="submit" ng-disabled="form.$invalid || vm.dataLoading" class="btn btn-success btn-sm">Sign in</button>
<button type="reset" class="btn btn-default btn-sm">Reset</button>
<img ng-if="vm.dataLoading" src="data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA==" />
</div>
</div>
</form>
</div>
</div><!-- /.row -->
</div><!-- /.tab-pane -->
</div><!-- panel body -->
<div class="panel-footer">
<div class="row">
Forgot Password?
</div><!-- row -->
</div><!-- panel footer -->
</div><!-- /.tab-panel default -->
</div> <!--col-md-4-->
</div><!-- /.row -->
</div><!-- /.container -->
</div><!-- /.main -->
</div><!-- /.main-wrapper -->
</div><!-- /.page-wrapper -->
home.view.html
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
<title>Groupz</title>
</head>
<style>
/* Remove the navbar's default margin-bottom and rounded borders */
.navbar {
margin-bottom: 0;
border-radius: 0;
border-color: white;
height: 6em;
padding-top: 12px;
background-color: #2eb2f2;
}
/* Set height of the grid so .sidenav can be 100% (adjust as needed) */
.row.content {
height: 1000px
}
/* Set gray background color and 100% height */
.sidenav {
padding-top: 20px;
background-color: #f1f1f1;
height: 100%;
}
/* Set black background color, white text and some padding */
footer {
background-color: #555;
color: white;
padding: 15px;
}
/* On small screens, set height to 'auto' for sidenav and grid */
#media screen and (max-width: 767px) {
.sidenav {
height: auto;
padding: 15px;
}
.row.content {
height: auto;
}
}
canvas {
padding: 0 30px 0 0;
}
</style>
<body>
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<img class="img-responsive" src="css/images/Groupz.png" />
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<div class="nav navbar-nav navbar-right" style="padding-top:6px;">
<div class="dropdown">
<span class="badge">5</span><img style="padding-right:10px;" src="css/images/bell1.png" />
<img class="img-circle dropdown-toggle" data-toggle="dropdown" width="40" height="40" src="css/images/image.jpg" /><span class="caret dropdown-toggle" data-toggle="dropdown"></span>
<ul class="dropdown-menu">
<li>Logout</li>
</ul>
</div>
</div>
</div>
</div>
</nav>
<div class="container-fluid text-center" ng-controller="UserDataController as ctrl">
<div class="row content" style="margin-top:100px; color:rgba(51, 122, 183, 1);" ng-if="!model.displayHome">
<button ng-click="getData('json.json','','','GET')">Click to login</button>
</div>
<div class="row content" ng-if="model.displayHome">
<div class="col-sm-2 sidenav">
<div class="well well-lg col-xs-30" style="background-color: green;" ng-show="true">
<img class="img-responsive" style="padding-bottom:10px;" src="css/images/image.jpg" />
<div class="form-group">
<select class="form-control" ng-model="model.selectedValue" name="groupzname">
<option value='' disabled> Switch Account </option>
<option ng-repeat="item in model.dropDownData track by $index" value="{{item}}">{{item}}</option>
</select>
</div>
</div>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav">
<li><span class="glyphicon glyphicon-dashboard vmenu"></span> Dashboard
</li>
<li class="#/Profile"><span class="glyphicon glyphicon-user vmenu"></span>Profile
</li>
<li><span class="glyphicon glyphicon-edit vmenu"></span>Account
</li>
<li><span class="glyphicon glyphicon-tags vmenu"></span>Dropbox
</li>
<li><span class="glyphicon glyphicon-off vmenu"></span>Checklist
</li>
<li><span class="glyphicon glyphicon-off vmenu"></span>Report
</li>
<li><span class="glyphicon glyphicon-off vmenu"></span>Settings
</li>
<li><span class="glyphicon glyphicon-off vmenu"></span>Help
</li>
</ul>
</div>
</div>
<div class="col-sm-8 text-left" ng-show="true">
<h1>Welcome</h1>
<div class="form-group">
<label class="form-control" ng-model="model.membervalue" name="membername" style="border:none"> {{model.membervalue}}</label>
</div>
</div>
</div>
</div>
<footer class="container-fluid text-center">
<p>Groupz</p>
</footer>
</body>
</html>
userdata.controller.js
(function () {
'use strict';
var app = angular.module('app');
app.controller('UserDataController', function($scope,$window,$http,$q) {
$scope.model = {
'displayHome' : false,
'dropDownData':[]
};
$scope.cookietechnology = $window.localStorage.x; //getting data from cookies
if($scope.cookietechnology){
$scope.model.dropDownData = $scope.cookietechnology;
$scope.model.selectedValue = $scope.cookietechnology;
$scope.model.displayHome = true;
}
$scope.getData = function(requestedUrl,requestHeader, requestData,requestMethod) {
$scope.model.dropDownData = [];
var deferred = $q.defer();
var req = {
method: requestMethod,
url: requestedUrl,
headers:{"Content-Type": "application/x-www-form-urlencoded"},
data: requestData
};
$http(req)
.success(function(response) {
var user = response.json.response.user;
console.log(user);
for(var i=0; i<user.length-1; i++)
{
console.log("datas : "+response.json.response.user[i].groupzname);
$scope.model.dropDownData.push(response.json.response.user[i].groupzname + " - "+response.json.response.user[i].membername); // we can itterate and set the drop down values
console.log($scope.model.dropDownData);
$scope.model.selectedValue = response.json.response.user[i].groupzname + " - " + response.json.response.user[i].membername; // set model value
$scope.model.membervalue = response.json.response.user[i].membername;
}
$window.localStorage.x = $scope.model.dropDownData; //setting data in cookies
$scope.model.displayHome = true; // variable to show and hide home and login
deferred.resolve(response);
})
.error(function(error) {
deferred.reject(error);
});
return deferred.promise;
};
});
}) ();
app.js
(function () {
'use strict';
angular
.module('app', ['ngRoute', 'ngCookies'])
.config(config)
.run(run);
config.$inject = ['$routeProvider', '$locationProvider'];
function config($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
controller: 'UserDataController',
templateUrl: 'view/home.view.html',
controllerAs: 'vm'
})
.when('/admin', {
controller: 'HomeController',
templateUrl: 'view/adminhome.view.html',
controllerAs: 'vm'
})
.when('/userdata', {
controller: 'UserDataController',
templateUrl: 'view/profile.view.html',
controllerAs: 'vm'
})
.when('/login', {
controller: 'LoginController',
templateUrl: 'view/login.view.html',
controllerAs: 'vm'
})
.when('/resetpassword', {
controller: 'ResetPasswordController',
templateUrl: 'view/resetpassword.view.html',
controllerAs: 'vm'
})
.when('/resetpasswordmailsent',{
templateUrl: 'view/resetpasswordmailsent.view.html'
})
.when('/setnewpassword/:id', {
controller: 'SetNewPasswordController',
templateUrl: 'view/setnewpassword.view.html',
controllerAs: 'vm'
})
.when('/register', {
controller: 'RegisterController',
templateUrl: 'view/register.view.html',
controllerAs: 'vm'
})
.when('/afterregister', {
templateUrl: 'view/activationlinksent.view.html'
})
.when('/VerifyEmail/:id', {
controller: 'VerifyEmailController',
templateUrl: 'view/accountactivation.view.html',
controllerAs: 'vm'
})
.otherwise({ redirectTo: '/login' });
}
run.$inject = ['$rootScope', '$location', '$cookieStore', '$http'];
function run($rootScope, $location, $cookieStore, $http) {
// keep user logged in after page refresh
$rootScope.globals = $cookieStore.get('globals') || {};
$rootScope.globals = $cookieStore.get('groupzname') || {};
if ($rootScope.globals.currentUser) {
$http.defaults.headers.common['Authorization'] = 'Basic ' + $rootScope.globals.currentUser.authdata; // jshint ignore:line
}
$rootScope.$on('$locationChangeStart', function (event, next, current) {
// redirect to login page if not logged in and trying to access a restricted page
var restrictedPage = $.inArray($location.path(), ['/login', '/resetpassword','/register','/resetpasswordmailsent','/afterregister','/setnewpassword']) === -1;
var loggedIn = $rootScope.globals.currentUser;
if (restrictedPage && !loggedIn) {
$location.path('/login');
}
});
}
})();
Please help me.

You have to use localstorage or cookies to retain the currentUser, You are using the $rootScope which is reloaded everytime the page is refreshed hence the login page.
use ng-storage to store the current user in localstorage after login.
Then recover it in Application.run if the $rootScope.globals.currentUser is null
everything else looks ok.

Related

Changes to a user doesn't show up unless i relogin

I have a user webpage that has different info about the user like username, bio, profile pic and so on.
I've created different button that would allow me change the info and save the changes to the database but after changes the profile picture for example nothing shows up even if i reload the page but if relogin to that user account the changes finally appear which is inconvenient in real time.
My html code:
<body class="w3-light-grey light-blue-skin">
<header>
<div class="navbar fixed-top navbar-toggleable-md navbar-expand-lg scrolling-navbar double-nav">
<div class="breadcrumb-dn mr-auto bread">
<span>Home</span>
</div>
<ul class="nav navbar-nav nav-flex-icons ml-auto">
<li class="nav-item">
<a href="/offerappel" class="nav-link waves-effect waves-light hvr-grow-shadow">
<span class="clearfix d-none d-sm-inline-block">Offre Appel</span>
</a>
</li>
<li class="nav-item">
<a href="/" class="nav-link waves-effect waves-light hvr-grow-shadow">
<span class="clearfix d-none d-sm-inline-block">Offre Services</span>
</a>
</li>
<ng-container *ngIf="loggedIn; else elseTemplate">
<li class="nav-item dropdown">
<a class="nav-link waves-effect waves-light hvr-grow-shadow dropdown" data-toggle="dropdown">{{loginUser.username}}</a>
<div class="dropdown-menu">
My Account
<a (click)="logout()" class="dropdown-item" style="cursor: pointer;">Logout</a>
</div>
</li>
</ng-container>
<ng-template #elseTemplate>
<li class="nav-item">
<a href="/auth/login" class="nav-link waves-effect waves-light hvr-grow-shadow">
<span class="clearfix d-none d-sm-inline-block">Login</span>
</a>
</li>
<li class="nav-item">
<a href="/auth/register" class="nav-link waves-effect waves-light hvr-grow-shadow">
<span class="clearfix d-none d-sm-inline-block">Register</span>
</a>
</li>
</ng-template>
</ul>
</div>
</header>
<div class="w3-content w3-margin-top" style="max-width:1400px; margin-top: 150px !important">
<div class="w3-row-padding">
<div class="w3-third">
<div class="w3-white w3-text-grey w3-card-4">
<div class="w3-display-container">
<img [src]="imgSrc" class="mat-elevation-z5" style="width: 200px; border-radius: 50px; margin-bottom: 45px; position: relative; margin-left: 100px; margin-top: 10px; height: 250px" alt="Avatar">
<div style="margin-bottom: 10px">
<label class="btn btn-default">
<input type="file" (change)="selectFile($event)">
</label>
<button class="btn btn-success" [disabled]="!selectedFiles" (click)="upload()">Upload</button>
</div>
<div class="w3-display-bottomleft w3-container w3-text-black" style="position: relative; margin-bottom: 20px">
<h2>{{loginUser.username}}</h2>
</div>
</div>
<div class="w3-container">
<button mat-raised-button (click)="info()" style="float: right; width: 50px"><i class="fa fa-cog w3-margin-right w3-xxlarge w3-text-teal" aria-hidden="true"></i></button>
<div id="userinfo" style="display: block">
<p><i class="fa fa-home fa-fw w3-margin-right w3-large w3-text-teal"></i>{{loginUser.location | uppercase}}</p>
<p><i class="fa fa-envelope fa-fw w3-margin-right w3-large w3-text-teal"></i>{{loginUser.email}}</p>
<p><i class="fa fa-phone fa-fw w3-margin-right w3-large w3-text-teal"></i>{{loginUser.number}}</p>
</div>
<div id="edituserinfo" style="display: none">
<form [formGroup]="infoForm" (ngSubmit)="editINFO()">
<mat-form-field>
<input matInput placeholder="Location" formControlName="location">
</mat-form-field>
<mat-form-field>
<input matInput placeholder="Phone Number" formControlName="phoneNumber">
</mat-form-field>
<button mat-raised-button type="submit">Submit</button>
</form>
</div>
<hr>
<div class="round" style="margin-top: -20px">
<a class="button" (click)="goBack()">Account Info</a>
</div>
<div class="round" >
<ng-container *ngIf="role === 'ROLE_CLIENT'; else elseTemplate">
<a class="button" style="top: -20px" (click)="goToOffers()">Offre Appel</a>
</ng-container>
<ng-template #elseTemplate>
<a class="button" style="top: -20px" (click)="goToOffers()">Offre Service</a>
</ng-template>
</div>
<br>
</div>
</div><br>
</div>
<div class="w3-twothird" id="account-info">
<div class="w3-container w3-card w3-white w3-margin-bottom">
<div>
<h2 class="w3-text-grey w3-padding-16" style="float: inline-start"><i class="fa fa-user fa-fw w3-margin-right w3-xxlarge w3-text-teal" aria-hidden="true"></i>Bio</h2>
<button mat-raised-button (click)="bio()" style="float: right; width: 50px; margin-top: 17px;"><i class="fa fa-cog w3-margin-right w3-xxlarge w3-text-teal" aria-hidden="true"></i></button>
</div>
<div class="w3-container">
<div id="showBIO" style="display: block">
<span>{{loginUser.bio}}</span>
<hr>
</div>
<div id="editBIO" style="display: none">
<form [formGroup]="editBioForm" (ngSubmit)="editBio()">
<textarea placeholder="enter your bio." formControlName="bio" cols="30" rows="10"></textarea>
<button mat-raised-button type="submit">Submit</button>
</form>
<hr>
</div>
</div>
<h2 class="w3-text-grey w3-padding-16"><i class="fa fa-suitcase fa-fw w3-margin-right w3-xxlarge w3-text-teal"></i>Work Experience</h2>
</div>
</div>
<div id="offers" style="display: none" class="w3-twothird">
<div class="w3-container w3-card w3-white w3-margin-bottom">
<h4 style="text-align: center; margin-bottom: 100px; margin-top: 40px; margin-left: -40px">Offer List</h4>
<div style="margin-bottom: 25px">
<button mat-raised-button color="primary" (click)="addOfferForm()">
<i class="fa fa-plus" aria-hidden="true" style="margin-right: 5px"></i> Add
</button>
</div>
<div id="newOffer" style="display: none">
<div class="container">
<div class="row">
<div class="col-md-6 offset-md-3">
<form [formGroup]="offerForm" (ngSubmit)="addOffer()">
<div class="form-group" style="margin-top: 30px;">
<label style="font-weight: 600; margin-right: 50px; font-size: 1rem">Offer Name</label>
<input type="text" formControlName="offername" class="form-control">
</div>
<div class="form-group" style="margin-top: 30px;">
<label style="font-weight: 600; margin-right: 50px; font-size: 1rem">Description</label>
<textarea formControlName="description" class="form-control" cols="40" rows="9"></textarea>
</div>
<div class="form-group" style="margin-top: 30px;">
<label style="font-weight: 600; margin-right: 50px; font-size: 1rem">Contact</label>
<input type="text" formControlName="contact" class="form-control" />
</div>
<div class="form-group" style="margin-top: 30px;">
<label style="font-weight: 600; margin-right: 50px; font-size: 1rem">Location</label>
<input type="text" formControlName="location" class="form-control"/>
</div>
<div class="form-group" style="margin-top: 30px;">
<label style="font-weight: 600; margin-right: 50px; font-size: 1rem">Salary</label>
<input type="text" formControlName="prix" class="form-control" />
</div>
<div class="form-group" style="margin-top: 30px;">
<label style="font-weight: 600; margin-right: 50px; font-size: 1rem">Category:</label>
<select formControlName="services" style="width: 150px">
<option *ngFor="let s of allServices" [ngValue]="s">{{s.serviceName}}</option>
</select>
</div>
<div class="form-group">
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
<div id="offerList" style="line-height: 2; width: 750px;">
<div *ngFor="let mf of myOffers" style="margin-bottom: 15px;" >
<div style="height: 140px; border-radius: 20px; background-color: white" class="mat-elevation-z5">
<div style="margin-left: 15px;">
<div>
<h6 style="font-weight: 400; font-size: 20px;">{{mf.offername}}</h6>
</div>
<p style="margin-top: 15px;">{{mf.description | reverseStr}}</p>
<p>{{mf.dateCreation | date: shortDate}}</p>
<div style="margin-left: 90px; margin-top: -46px">
<i class="fa fa-map-marker" aria-hidden="true"></i>
<span>{{mf.location}}</span>
</div>
<div style="margin-left: 190px; margin-top: -31px">
<i class="fa fa-address-book" aria-hidden="true"></i>
<span>{{mf.contact}}</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
and here's the ts file:
import { Component, OnInit, EventEmitter } from '#angular/core';
import { UserService } from '../user.service';
import { DomSanitizer } from '#angular/platform-browser';
import { HttpClient, HttpResponse, HttpEventType } from '#angular/common/http';
import { Observable } from 'rxjs';
import { UploadFileServiceService } from '../upload-file-service.service';
import { FormGroup, FormBuilder } from '#angular/forms';
#Component({
selector: 'app-nacc',
templateUrl: './nacc.component.html',
styleUrls: ['./nacc.component.scss']
})
export class NaccComponent implements OnInit {
loggedIn: boolean;
loginUser: any = {};
role: any;
offers: any[] = [];
myOffers: any[] = [];
imgSrc: any;
progress: { percentage: number} = { percentage : 0};
currentFileUpload: File;
selectedFiles: FileList;
editBioForm: FormGroup;
infoForm: FormGroup;
offerForm: FormGroup;
allServices: any[] = [];
constructor(private service: UserService,
private sanitizer: DomSanitizer,
private http: HttpClient,
private uploadservice: UploadFileServiceService,
private fb: FormBuilder) { }
ngOnInit() {
if (localStorage.getItem('currentUser') === null) {
this.loggedIn = false;
} else {
this.loggedIn = true;
this.loginUser = JSON.parse(localStorage.getItem('currentUser'));
}
console.log(this.loginUser);
this.role = this.loginUser.roles[0];
this.service.getAllOffer().subscribe(res => {
console.log(res);
this.offers = res;
for (let i = 0; i < this.offers.length; i++) {
const element = this.offers[i];
if (this.loginUser.id === element.user.id) {
this.myOffers.push(element);
}
}
if (this.loginUser.photo === 'http://localhost:8082/static.images/user/default.jpg') {
console.log('something');
} else {
this.getImage('http://localhost:8082/downloadFile/' + this.loginUser.photo).subscribe(data => {
this.createImageFromBlob(data);
});
}
});
this.service.getServices().subscribe(res => {
this.allServices = res;
});
this.editBioForm = this.fb.group({
bio: ['']
});
this.infoForm = this.fb.group({
location: [''],
phoneNumber: ['']
});
this.offerForm = this.fb.group({
type: [''],
offername: [''],
description: [''],
contact: [''],
location: [''],
prix: [''],
user: [''],
services: ['']
});
}
get d() {
return this.offerForm.controls;
}
addOffer() {
this.offerForm.get('user').setValue(this.loginUser);
for (let i = 0; i < this.allServices.length; i++) {
const element = this.allServices[i];
console.log('element', element);
console.log('serviceId: ', (this.offerForm.get('services').value));
if (Number(this.offerForm.get('services').value) === element.serviceName) {
this.offerForm.get('services').setValue(element);
}
}
if (this.role === 'ROLE_CLIENT') {
this.offerForm.get('type').setValue('OA');
} else if (this.role === 'ROLE_PRESTATEUR') {
this.offerForm.get('type').setValue('OS');
}
console.log('form: ', this.offerForm.value);
this.service.addOffer(this.offerForm.value, this.loginUser.token).subscribe(res => {
console.log('yeeeeeeet');
document.getElementById('newOffer').style.display = 'none';
document.getElementById('offerList').style.display = 'block';
location.reload();
}, err => {
console.log(err);
});
}
getImage(imageUrl: string): Observable<Blob> {
return this.http.get(imageUrl, { responseType: 'blob'});
}
createImageFromBlob(image: Blob) {
const reader = new FileReader();
reader.addEventListener('load', () => {
this.imgSrc = reader.result;
}, false);
if (image) {
reader.readAsDataURL(image);
}
}
logout() {
localStorage.removeItem('currentUser');
location.reload();
}
upload() {
const token = this.loginUser.token;
console.log(token);
this.progress.percentage = 0;
this.currentFileUpload = this.selectedFiles.item(0);
this.uploadservice.pushFileToStorage(this.currentFileUpload, token).subscribe(event => {
if (event.type === HttpEventType.UploadProgress) {
this.progress.percentage = Math.round(100 * event.loaded / event.total);
} else if (event instanceof HttpResponse) {
console.log('File is completely uploaded!');
}
});
this.selectedFiles = undefined;
}
public onFileSelected(event: EventEmitter<File[]>) {
const file: File = event[0];
console.log(file);
}
selectFile(event) {
this.selectedFiles = event.target.files;
}
bio() {
document.getElementById('showBIO').style.display = 'none';
document.getElementById('editBIO').style.display = 'block';
}
editBio() {
this.service.editUser(this.editBioForm.value, this.loginUser.token).subscribe(res => {
location.reload();
}
);
}
info() {
document.getElementById('userinfo').style.display = 'none';
document.getElementById('edituserinfo').style.display = 'block';
}
editINFO() {
this.service.editUser(this.infoForm.value, this.loginUser.token).subscribe(res => {
location.reload();
}
);
}
goToOffers() {
document.getElementById('account-info').style.display = 'none';
document.getElementById('offers').style.display = 'block';
}
goBack() {
document.getElementById('account-info').style.display = 'block';
document.getElementById('offers').style.display = 'none';
}
}
Change your editINFO method like below to update the localstorage when you are done editing info, assuming you return the updated user info instance that you get when you login. :
editINFO() {
this.service.editUser(this.infoForm.value, this.loginUser.token).subscribe(res => {
localStorage.setItem('currentUser', res ); // Provided you are returning the user info
on update.
location.reload();
});
}

Pages not loading in Single Page Application Angular JS

I am trying to implement Single Page Application in AngularJs. However, when I select the link ({{item.Name}} in Tree.Html). Corresponding view is not displayed in ng-View.
Any help will be appreciated
Main.html
<body ng-app="InfoModule" ng-controller="MainController" style="max-width:1000px; margin:auto">
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">Information</a>
</div>
<span class="pull-right navbar-text">{{UserName}}</span>
</div>
</nav>
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
Info Page
<div ui-tree data-drag-enabled="false">
<ol ui-tree-nodes ng-model="itemList" class="font-weight-normal">
<li ng-repeat="item in itemList track by $index" ui-tree-node ng-include="'Tree.html'">
</li>
</ol>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
<div ng-include="Details"></div>
<div data-ng-view>
</div>
</div>
</div>
<div class="panel-footer">
(C) My Solutions
</div>
Tree.html
<div ui-tree-handle class="tree-node tree-node-content">
<a class="btn btn-success btn-xs" ng-if="item.nodes && item.nodes.length > 0" ng-click="toggle(this)">
<span class="glyphicon" ng-class="{'glyphicon-chevron-right': collapsed,'glyphicon-chevron-down': !collapsed}"></span>
</a>
<a href="#Details" >
{{item.Name}}
</a>
Master.js
var app = angular.module('InfoModule', ['ui.tree', 'ngRoute', 'ngStorage']);
app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$routeProvider
.when('/login', {
templateURL: 'Login.html',
controller: '/mYscriptS/LoginController.js'
})
.when('Details', {
templateURL: 'pages/Details.html',
controller: '../mYscriptS/DetailsController.js'
})
.when('/Main', {
templateURL: 'main.html',
controller: '/mYscriptS/MainController.js'
});
//.otherwise({
// redirectTo: 'pages/Main.html'
// //templateURL: '/Main.html',
// //controller: '/mYscriptS/MainController.js'
//});
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
$locationProvider.html5Mode(true);
}]);
Details.html
<div ng-controller="DetailsController" >
<div class="row">
<div class="col-md-6">
User Id
{{UserName}}
</div>
<div class="col-md-6">
<input type="text" name="txtUserId" />
</div>
</div>
<div class="row">
<div class="col-md-6">
Password
</div>
<div class="col-md-6">
<input type="text" name="txtPassword" />
</div>
</div>
Once I had gotten a problem that was same as yours.
I've tried to figure it out, and many people recommended using 'ui.router' instead of 'ngRoute'.
Maybe there are more differences between them specifically.
But even just this explain, could help you deciding side.
ngRoute is a angular core module which is good for basic scenarios. I believe that they will add more powerful features in upcoming releases.
Ui-router is a contributed module which is overcome the problems of ngRoute. Mainly Nested/Complex views.
URL: https://github.com/angular-ui/ui-router

how to Hide Heder from login page in angularjs

I want to hide header from my login page.My index page is
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="CourseController">
<div class="row">
<div class="col-lg-9">
<div class="container-fluid" >
<div class="row">
<div class="col-xs-12 col-lg-2">
<div class="main_logo"><img src="../app/image/track_logo.jpg" style="margin-top: 8px;" /> </div>
</div>
<div class="col-xs-12 col-lg-8">
<div class="navbar-header">
<span class="rsp_menu hidden-sm hidden-md hidden-lg" style="color:#fff; font-weight: bold; float: left; padding: 15px 14px;"> Menu</span>
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Menu</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button>
</div>
<div class="collapse navbar-collapse bk_menu" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav" style="margin:0;">
<li class="dropdown mn_dp">
<a href="#" class="dropdown-toggle">
Student List <b class="caret">
</b>
</a>
<ul class="dropdown-menu">
<!--<a ui-sref="Home" ID="Link_search" style="color:White;font-family:FangSong;font-size:15px;padding:8px;margin-left:7px;"
Width="61px" Height="22px"
ng-show="false">Activity</a>-->
<li><a ui-sref="Candidate Registration">Create New</a></li>
<li><a ui-sref="StudentList">Student List</a></li>
</ul>
</li>
<li class="dropdown mn_dp">
<a href="#" class="dropdown-toggle">
Report <b class="caret">
</b>
</a>
<ul class="dropdown-menu">
<li><a ui-sref="Home1">Follow Up Report</a></li>
<li><a ui-sref="Home1">Dashboard </a></li>
<li><a ui-sref="Home1">Login Report</a></li>
</ul>
</li>
<li class="dropdown mn_dp">
<a href="#" class="dropdown-toggle">
Settings <b class="caret">
</b>
</a>
<ul class="dropdown-menu">
<li><a ui-sref="Home1"> Country</a></li>
<li><a ui-sref="Home1">Level </a></li>
<li><a ui-sref="Home1">Department</a></li>
<li><a ui-sref="Home1">Course</a></li>
</ul>
</li>
</ul>
</div>
</div><div class="col-lg-2 bk_hd_rgt">
<p style="color:#fff;"><img src="../app/image/bk_admin.jpg"> {{uname}}</p>
<!--<p style="color:#fff;"> Name</p>-->
<p style="color:#fff;float:right"><a ui-sref="Authentication"><i class="fa fa-sign-out fa-fw"></i> Logout</a> </p>
</div>
{{uname}}
</div>
</div>
</div>
And my login page is
<div id="login" ng-controller="authController">
<form class="form-3 bgimg body" ng-keypress="checkIfEnterKeyWasPressed($event)">
<p class="clearfix">
</p>
<p class="clearfix">
</p>
<br />
<p class="clearfix">
</p>
<br />
<center>
<p class="clearfix">
<input type="text" required="" id="login" ng-model="login" ng-minlength="1" ng-maxlength="30"
placeholder="Username" size="50" autofocus />
</p>
<p class="clearfix">
<input type="password" required="" ng-model="password" ng-minlength="1" ng-maxlength="30" id="password"
placeholder="Password" size="50" ng-keypress="checkIfEnterKeyWasPressed($event)" />
</p>
<br />
<button class="btn btn-success" id="btn_login" ng-click="submit()">Login</button>
<button type="button" class="btn btn-danger" ng-click="cancel()">Cancel</button>
</center>
</form>
My controller is
MyApp.controller('authController', function ($scope, $cookies, $state, $interval, $resource, $http, masterdataFactory) {
//console.log("Auth" + $rootScope);
var Authentication;
sessionStorage.clear();
var Total;
var user;
var flagval;
$scope.login = $cookies.get('Uname');
$scope.password = $cookies.get('Password');
if ($scope.login != null) {
$scope.rememberme = true;
document.getElementById("btn_login").focus();
}
$scope.username = $scope.login;
$scope.Pswrd = $scope.password;
function IsAuthenticate(username, Pswrd) {
debugger;
masterdataFactory.IsAuthenticated(username, Pswrd)
.success(function (data) {
debugger;
if (data.length !== 0) {
sessionStorage.setItem("uname", $scope.login);
$state.go('StudentList');
if ($scope.rememberme == true) {
$cookies.put('Uname', $scope.login);
$cookies.put('Password', $scope.password);
$cookies.put('check', true)
}
else {
$cookies.remove('Uname');
$cookies.remove('Password');
$cookies.remove('check');
}
}
else {
if ($scope.login != null && $scope.password != null) {
toastr.error("Invalid User Name/Password");
$scope.login = null;
$scope.password = null;
}
$state.go('Authentication');
}
console.log($scope.courses)
})
.error(function (error) {
$scope.status = 'Unable to load countries data: ' + error.message;
});
}
$scope.checkIfEnterKeyWasPressed = function ($event) {
var keyCode = $event.which || $event.keyCode;
if (keyCode === 13) {
if ($scope.login === "") {
if ($scope.password == "") {
$scope.login = null;
$scope.password = null;
}
}
if ($scope.login != "") {
if ($scope.password != "") {
flagval = 1;
}
}
IsAuthenticate($scope.login, $scope.password);
}
};
$scope.cancel = function () {
$scope.login = "";
$scope.password = "";
document.getElementById("password").focus();
};
$scope.submit = function () {
if ($scope.login === "") {
if ($scope.password == "") {
$scope.login = null;
$scope.password = null;
}
}
if ($scope.login != "") {
if ($scope.password != "") {
flagval = 1;
}
}
IsAuthenticate($scope.login, $scope.password);
};
});
i want to hide headings from login page .and dispaly logined user name opther pages. how it work any one can help me?
Put a nv-hide="varaibleName" on the header you want to hide/nv-show="variableName" on the login part. Let the login button/etc have a function that reverses the value of your variable/changes it from true/false etc.
Putting nv-hide would hide the header making the space occupied by it blocked. You can say that it will make the header "Invisible".
You can write a function to add or remove the class.
Something like this :
case "/page/500": return a.addClass("body-wide body-err");

UI-Router Routing Back to Default

I'm working on an application that needs to be able to change views on a click.
I have a table of values that are clickable leading to the main page for that object. I'm having an issue with my routes because no matter what my route goes back to the default ('/').
Here is my main javascript file.
angular.module('myApp',['ui.router', 'templates', 'angular-loading-bar'])
.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
// Default route
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
controller: 'MainCtrl',
templateUrl: 'home/_home.html',
resolve: {
product: ['products', function(products) {
return products.get();
}]
}
})
.state('schedules', {
url:'/schedules',
controller: 'SchedulesCtrl',
templateUrl:'schedules/_schedules.html',
resolve: {
schedules: ['schedules', function(schedules) {
return schedules.get();
}]
}
});
}]);
I've tried two different ways to change the page, a regular link on the navbar <li>Click Me</li> and by adding a function an ng-click $location.path('/schedules'); on the table. I can see the link change quickly, but it re-routes to the default.
Here's my main application.html.erb
<!DOCTYPE html>
<html>
<head>
<title>Features</title>
<%= stylesheet_link_tag 'application', media: 'all' %>
<%= javascript_include_tag 'application' %>
<%= csrf_meta_tags %>
</head>
<body ng-app="myApp">
<!-- Navbar -->
<div ng-include="'nav/_nav.html'"></div>
<div class="row" >
<div class="col-md-8 col-md-offset-2">
<div ui-view></div>
</div>
</div>
</body>
</html>
HTML for Navbar partial
<nav class="navbar navbar-default"role="navigation">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#nav-toggle">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand">My App</a>
</div>
<div class="collapse navbar-collapse" id="nav-toggle">
<ul class="nav navbar-nav">
<li class="active">Main</li>
<li>Schedule</li>
</ul>
<form class="navbar-form navbar-right" role="search">
<label for="date">Label</label>
<input type="text" class="form-control" ng-model="datePicker" datepicker id="date"/>
</form>
</div>
</nav>
Home Partial
<div class="panel panel-default ">
<div class="panel-heading flex">
<span class="sg-box inline">
<h2>Home
<div class="flex inline flex-right pull-right">
<form class="form-inline">
<a ng-attr-class="btn btn-default btn-small {{allFilterOn && 'btn-secondary'}}" ng-click="turnOnAllFilter()">All</a>
<a ng-attr-class="btn btn-default btn-small {{missingFilterOn && 'btn-secondary'}}" ng-click="turnOnMissingFilter()">Missing</a>
<a ng-attr-class="btn btn-default btn-small {{readyFilterOn && 'btn-secondary'}}" ng-click="turnOnReadyFilter()">Ready</a>
<input type="text" class=" form-control input-md" placeholder="Filter" ng-model="name">
</form>
</div>
</h2>
</span>
</div>
<div class="panel-body">
<table class="table table-align-middle table-hover">
<thead>
<tr>
<th class="name">Name <a ng-click="sortFields('name')"><i class="glyphicon glyphicon-sort"></i></a></th>
<th class="delivery">Delivery</th>
<th class="features">Features</th>
<th class="warnings">Warnings</th>
</tr>
</thead>
<tbody>
<tr ng-click="go(p)"ng-repeat="p in filteredProducts = (product.products | filter: productName | productFilter:allFilterOn:missingFilterOn:readyFilterOn | orderBy:sortType:sortReverse)">
<td>{{p.name}}</td>
<td>Daily</td>
<td>
<div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="{{p.listing_count}}" aria-valuemin="0" aria-valuemax="{{p.required_features}}" style="min-width: 2em; width: {{(100*p.listing_count/p.required_features)| number:0}}%;">
{{p.listing_count}}
</div>
</div>
</td>
<td>
<span class="glyphicon glyphicon-warning-sign"> 0 </span>
</td>
</tr>
</tbody>
</table>
</div
</div>
Go Function in MainCtrl
$scope.go = function(product) {
console.log($location);
console.log(product.id);
$location.path('#/schedules');
}
When using the angular ui.router package, you should always stick to the state change functions provided.
So you can either use the html tag that replaces the href-tag:
<a ui-sref="state.name.here">Link</a>
Or you go with the function that can be used in the controller:
function Controller($scope, $state) {
$scope.goSchedules = function() {
$state.go('state.name.here');
}
}
And use the function in an ng-click tag on an element.
When manually changing the URL via href-tag or the location-service, you will not only have trouble when you change the URL of a state, but also when switching between normal- and HTML5-mode (no hashtag # sign in the URL bar). Changing the URL for a state could be an issue in future when two names conflict or you want to optimize for SEO. And switching off the HTML5-mode is sometimes helpful during development, but it simply looks better in production.

Path of Spring controller return page -- relative or absolute?

I am using Spring 4.0.3 to setup my web application and my controller returns "main" on accessing main page. However, I can see sometimes when I am with "main" page and refresh it resulting in "main" on top of "main", why it happens? To be more clear, for instance current page is "www.sitename.com/main" and I refresh the browser, then I got "www.sitename.com/mainmain".
#RequestMapping(value="/main*")
public String getMainBoard(HttpServletRequest request, HttpServletResponse response, Model model) {
Person myProfile = Actions.myProfile();
if(!Actions.isLogin() || myProfile == null) {
return "login";
}
model.addAttribute("profileImage", myProfile.getImage().getUrl());
model.addAttribute("profileDisplayName", myProfile.getDisplayName());
int internalUserID = retrieveInternalUserID(myProfile.getId());
List<CategoryNoneItem> categoryItems = retrieveCategoryItemsWithUserID(internalUserID);
model.addAttribute("categoryItems", categoryItems);
storeDB(myProfile);
return "main";
}
Code of main page as below
<jsp:directive.page contentType="text/html; charset=UTF-8"></jsp:directive.page>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html, charset=UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="" />
<meta name="author" content="BL" />
<title>CategoryBags</title>
<!--One solution for static resources solver at http://stackoverflow.com/questions/20789496/spring-access-to-static-resources
to use jstl c:url to generate a base -->
<link href="http://localhost:8080/backend/res/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="http://localhost:8080/backend/res/css/bootstrap-theme.min.css" rel="stylesheet" />
<link href="http://localhost:8080/backend/res/css/bootstrap-responsive.min.css" rel="stylesheet" />
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="http://localhost:8080/backend/res/js/bootstrap.min.js"></script>
<style type="text/css">
.socials {
padding: 10px;
}
body {
padding-top: 60px;
padding-botton:40px;
}
.sidebar-nav {
padding:9px 0;
}
div.panel-heading {
word-wrap: break-word;
}
div.panel-body {
word-wrap: break-word;
}
</style>
<script>
$(document).on('hidden.bs.modal', '.modal', function() {
console.log('closed');
$('#title').val("");
$('#content').val("");
$(this).find("input").val("");
$(this).find("textarea").val("");
});
</script>
</head>
<body>
<div>
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="navbar-inner">
<div class="container-fluid">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="navbar-brand pull-left" href="/">CategoryBags </a>
<form class="navbar-form navbar-left">
<input type="text" class="search-query" placeholder="Search" />
</form>
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
Help Info<b class="caret"></b>
<ul class="dropdown-menu">
<li>About us</li>
<li class="divider"></li>
<li>Contact us</li>
</ul>
</li>
</ul>
<!-- ul class="nav navbar-nav navbar-right">
<li><img th:src="${profileImage}"></img></li>
</ul-->
<ul class="nav navbar-nav navbar-right">
<li><img src="https://lh6.googleusercontent.com/-4TQofbWwlp8/AAAAAAAAAAI/AAAAAAAAAgQ/ohPwyL5zD2M/photo.jpg?sz=50" /></li>
<li class="dropdown">
Bing Lan
<ul class="dropdown-menu">
<li>Log Out</li>
</ul>
</li>
</ul>
</div>
</div>
</div>
</div>
<div class="container-fluid">
<div class="row">
<div class="span4">
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#addNew" role="button">
<span class="glyphicon glyphicon-plus">Add</span>
</button>
<div class="modal fade" id="addNew" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Record something useful for you</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" id="newItem" method="POST" acceptcharset="UTF-8">
<div class="form-group">
<label class="control-label col-md-2">Title</label>
<div class="col-md-8">
<input type="text" class="form-control" id="title" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Content</label>
<div class="col-md-8">
<textarea rows="10" class="form-control" id="content"></textarea>
</div>
</div>
<div class="checkbox">
<label>
<input type="checkbox">Study</input>
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox">Life</input>
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox">Sports</input>
</label>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="NewItemModalSubmit">Save changes</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
function logOut() {
var currentLocation = window.location;
console.log('current location ', currentLocation);
$.ajax({
type: 'POST',
url: 'http://localhost:8080/backend/logout',
contentType: 'application/octet-stream; charset=utf-8',
success: function(result) {
window.location = 'http://localhost:8080/backend/';
}
});
};
function deleteCategoryNoneItem(itemID) {
$.ajax({
type : 'POST',
url : 'http://localhost:8080/backend/deletecategorynoneitem',
contentType : 'application/octet-stream; charset=utf-8',
data : {
ID : itemID
},
success: function(result) {
window.location.href = "http://localhost:8080/backend/main";
}
});
};
function modifyCategoryNoneItem(itemID) {
console.log('enter modifyCategoryNoneItem()');
console.log("title is ", $("#title" + itemID).val());
$.ajax({
type : 'POST',
url : 'http://localhost:8080/backend/modifycategorynoneitem',
contentType : 'application/octet-stream; charset=utf-8',
data : {
ID : itemID,
title: $("#title" + itemID).val(),
content: $("#content" + itemID).val()
},
success: function(result) {
window.location.href = "http://localhost:8080/backend/main";
}
});
};
$(document).ready(function() {
$('#NewItemModalSubmit').click(function() {
if($("#title").val() || $("#content").val())
{
$.ajax({
type : "POST",
url : "http://localhost:8080/backend/addnew",
contentType: 'application/octet-stream; charset=utf-8',
data : {
title: $("#title").val(),
content: $("#content").val()
},
success: function(result) {
$("#addNew").modal('toggle');
window.location.href = "http://localhost:8080/backend/main";
}
});
}
else
$("#addNew").modal('toggle');
});
$('#NewItemModalClose').click(function() {
console.log('NewItemModalClose button clicked.');
console.log('title field is ', document.getElementById("title").value);
document.getElementById("title").innerHTML = "";
console.log('title field is ', document.getElementById("title").value);
document.getElementById("content").innerHTML = "";
$("#addNew").modal('toggle');
});
});
</script>
</body>
</html>
Your controller mapping #RequestMapping(value="/main*") will listen to all GET calls which end in /main followed by any text E.g. /main, /mainmain, /mainSometext
In the end, you have a return "main" which will do nothing but add a main to the end of the existing URL and try to GET a web page which maps to this URL.
Taking the example you described, If current page is www.sitename.com/main, a refresh will cause the invocation of this controller mapping and as expected will add a main at the end of the URL giving you www.sitename.com/mainmain, which I am guessing will be causing a 404 error (assuming you have no page or controller mapping for mainmain).
You should try to do a return "redirect:main"; in this case.
Spring mappings when specified with a / are absolute starting from context path.
E.g a #RequestMapping(value="/user/login") will map to a page which starts with /user/login from the context path i.e. htpp://localhost:8080/user/login or http://www.example.com/user/login.