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.
Related
I got problem with my Razor page application. I already use render section for footer:
<footer class="border-top footer text-muted">
#RenderSection("footer", required: false)
<div class="container">
© 2021 - EmployeeBook - <a asp-area="" asp-page="/Privacy">Privacy</a>
</div>
</footer>
and use it also in employee list
#page
#model EmployeeBook.Pages.Employees.EmployeesModel
#{
ViewData["Title"] = "Employees";
}
<h1>Employees razor page</h1>
<br />
<form method="get">
<div class="form-group">
<div class="input-group">
#*asp-for two ways data binding*#
<input type="search" class="form-control" asp-for="SearchTerm" />
<span class="input-group-btn">
<button class="btn btn-default">Search</button>
</span>
</div>
</div>
</form>
#foreach (var employee in Model.Employees)
{
<partial name="_Summary" model="employee" />
}
#*Remember about nullable values added to onGet/onPost if we want to use this method there*#
<div>
<a asp-page="./EditEmployee" class="btn btn-primary">Add nefw Employee</a>
</div>
#section footer {
<div>
#Model.Message
</div>
}
Result of that is something like that:
Im trying to use _summary partial view to display details of employees instead of common list. Could someone tell me where the problem can be? I use just classes from bootstrap. It start to works not correct when I add more employees.
#using EmployeeBook.Core
#*from lower case define just type of object into view*#
#*from upper case this is model property where we can go into*#
#model Employee
<div class="modal-content">
<div class="modal-header">
<h3>#Model.Name</h3>
</div>
<div class="modal-body">
<span>Type of employee #Model.TypeOfEmployee</span>
</div>
<div class="modal-footer">
<a class="btn btn-light"
asp-page="./EmployeeDetails"
asp-route-employeeId="#Model.Id">
Details
</a>
<a class="btn btn-light"
asp-page="./EditEmployee"
asp-route-employeeId="#Model.Id">
Edit
</a>
<a class="btn btn-danger"
asp-page="./Delete"
asp-route-employeeId="#Model.Id">
Delete
</a>
</div>
</div>
I want to and remove a tr when I click a button, but it doesn't disappear (my function to delete it from the DB works fine, it just stays in the screen until I refresh).
It's like it doesn't take the ID properly.
Any hints?
HTML
<tbody>
<?php foreach ($elementos as $elementos): ?>
<tr class="tr_test" data-id="<?php echo $elementos['ELDI_Id']; ?>">
...
AJAX
$.ajax({
url: $("#base_url").attr("valor") + "diccionarios/eliminar_elementos_diccionario",
type: 'POST',
data: { id:id_eldi },
success: function(response){
// THIS WORKS FINE, BUT I'M ASKED TO DO IT THE OTHER WAY
/* $(el).closest('tr').fadeOut(800, function(){
$(this).remove();
}); */
$('tr[data-id="' + id_eldi + '"]').fadeOut(800, function(){
$(this).remove();
});
}
});
Thanks for your time!
EDIT
Populated table's html, as asked in a comment:
<section class="content">
<div class="container-fluid">
<div class="block-header">
<div class="alert alert-info">
<strong>
Elementos del Diccionario 2 </strong>
<!-- <strong>
Elementos del Diccionario </strong> -->
</div>
</div>
<div class="row clearfix">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="card">
<div class="body">
<!-- <div>
<a class="nav-link" href="http://localhost/bpg/diccionarios/nuevo_elemento_diccionario">Añadir elemento</a>
</div> -->
<!-- BOTÓN AÑADIR ELEMENTO MODAL -->
<a title="Añadir" style="margin-bottom:20px;" class="btn btn-primary" data-toggle="modal" data-target="#Modal_Add">
<i class="material-icons">add</i>Nuevo elemento
</a>
<div class="table-responsive">
<table id="tabla-elementos" class=" display table table-bordered table-striped table-hover tabla-usuarios">
<thead>
<tr>
<th>Key</th>
<th>Display</th>
<th>Acciones</th>
<!-- <th>Acciones</th> -->
</tr>
</thead>
<tbody>
<tr class="tr_test" data-id="347">
<td>prueba_1</td>
<td>Prueba Uno</td>
<td>
<span class="btn btn-default editar_elemento" id='347' value="347">
<a href="http://localhost/bpg/diccionarios/elemento_diccionario/347" title="Editar">
<i class="material-icons">edit</i>
</a>
</span>
<span class="btn btn-default borrar_elemento" id='347' value="347">
<i class="material-icons">delete_outline</i>
</span>
</td>
</tr>
<tr class="tr_test" data-id="348">
<td>prueba_2</td>
<td>Prueba Dos</td>
<td>
<span class="btn btn-default editar_elemento" id='348' value="348">
<a href="http://localhost/bpg/diccionarios/elemento_diccionario/348" title="Editar">
<i class="material-icons">edit</i>
</a>
</span>
<span class="btn btn-default borrar_elemento" id='348' value="348">
<i class="material-icons">delete_outline</i>
</span>
</td>
</tr>
<tr class="tr_test" data-id="351">
<td>prueba_3</td>
<td>Prueba Tres</td>
<td>
<span class="btn btn-default editar_elemento" id='351' value="351">
<a href="http://localhost/bpg/diccionarios/elemento_diccionario/351" title="Editar">
<i class="material-icons">edit</i>
</a>
</span>
<span class="btn btn-default borrar_elemento" id='351' value="351">
<i class="material-icons">delete_outline</i>
</span>
</td>
</tr>
<tr class="tr_test" data-id="353">
<td>prueba_4</td>
<td>Prueba Cuatro</td>
<td>
<span class="btn btn-default editar_elemento" id='353' value="353">
<a href="http://localhost/bpg/diccionarios/elemento_diccionario/353" title="Editar">
<i class="material-icons">edit</i>
</a>
</span>
<span class="btn btn-default borrar_elemento" id='353' value="353">
<i class="material-icons">delete_outline</i>
</span>
</td>
</tr>
</tbody>
</table>
</div>
Volver a Diccionarios
</div>
</div>
</div>
</div>
</div>
I'm not sure if it's the cause of your problem, but your HTML/PHP is incorrect, it should read:
<tbody>
<?php foreach ($elementos as $elemento): ?>
<tr class="tr_test" data-id="<?php echo $elemento['ELDI_Id']; ?>">
...
try add it's table parent as identifier:
$('button#btn').on('click', function() {
$('table#table tr[data-id="1"]').fadeOut(800, function(){
$(this).remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table">
<tbody>
<tr data-id="1">
<td>row</td>
</tr>
</tbody>
</table>
<button type="button" id="btn">
remove
</button>
only using tr[data-id=""] might be too broad for the DOM to find that element.
SOLUTION FOUND
I wasn't assigning data-id to the new appended rows.
JQUERY/AJAX
Fade and remove the tr:
$("tr[data-id-fila="+theID+"]").fadeOut(800, function(){
$(this).remove();
});
New appended row (AJAX gets result from model and controller using insert_id())
var html =
'<tr data-id-fila="' + result.newID +'">'+
..............
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
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.
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.