Disable routing on page refresh in angular js - html

I have a route provider like this
app.config(function ($routeProvider, $locationProvider){
$locationProvider.hashPrefix('');
$routeProvider
.when('/', {
templateUrl: 'login.html',
controller: 'loginCtrl'
})
.when('/home', {
resolve:{
"check":function($location, $rootScope){
if(!$rootScope.loggedIn){
$location.path('/');
}
}
},
templateUrl:'home.html',
controller: 'homeCtrl'
})
.otherwise({
redirectTo: '/'
});
});
login.html is the first page of my app.
But after login, on reloading any page that will ends up in the login.html page
I want other pages keep alive on refresh and login.html as my opening page

Reloading page will recreate $rootScope every time. So you need to store login details in any storage like localstorage.
http://blog.teamtreehouse.com/storing-data-on-the-client-with-localstorage
This link might help you. you need to store data once you successfully logged in. and get stored data and validate the use while resolving url.

scotchApp.config(function($stateProvider, $urlRouterProvider, $compileProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$compileProvider.debugInfoEnabled(false);
// route for the home page
$stateProvider
.state('home', {
url: '/home',
templateUrl : 'pages/home.html',
controller : 'mainController'
})
// route for the about page
.state('about', {
url: '/about',
templateUrl : 'pages/about.html',
controller : 'aboutController'
})
// route for the contact page
.state('contact', {
url: '/contact',
templateUrl : 'pages/contact.html',
controller : 'contactController'
});
$urlRouterProvider.otherwise('home');
});
Try something like this.

Related

angularjs route - jump to specific page section on route link

I am trying to make some kind of a mix between an Angular anchor and routing...
I do have it working in the home page, since the anchor sections are there, however, if I am in another page, it does not.
Can anyone point me in the right direction on how to do it correctly, please?
Here´s what I have so far
freddoApp.config(function($routeProvider, $locationProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl : 'pages/home/home.html',
controller : 'mainController'
})
// route for the productos page
.when('/productos', {
templateUrl : 'pages/home/home.html',
controller : 'mainController'
})
// route for the unico page
.when('/unico', {
templateUrl : 'pages/home/home.html',
controller : 'mainController'
})
// route for the sabores page
.when('/sabores', {
templateUrl : 'pages/home/home.html',
controller : 'mainController'
})
// route for the locales page
.when('/locales', {
templateUrl : 'pages/locales/locales.html',
controller : 'storeController'
})
// route for the servicios page
.when('/servicios', {
templateUrl : 'pages/servicios/servicios.html',
controller : 'servicesController'
})
// route for the about page
.when('/about', {
templateUrl : 'pages/about/about.html',
controller : 'aboutController'
})
// route for the contact page
.when('/contact', {
templateUrl : 'pages/contact/contact.html',
controller : 'contactController'
});
// use the HTML5 History API
$locationProvider.html5Mode(true);
});
/............................./
freddoApp.controller('mainController', function($scope, $location, $anchorScroll) {
$scope.scrollTo = function(id) {
$location.hash(id);
$anchorScroll();
};
/............................./
(HTML)
<div id="freedo-nav-bar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a ng-click="scrollTo('productos')">Productos</a></li>
<li><a ng-click="scrollTo('unico')"> Freddo Único</a></li>
<li><a ng-click="scrollTo('sabores')"> Sabores</a></li>
<li> Locales</li>
<li> Servicios</li>
<li> Nosotros</li>
<li> Contacto</li>
</ul>
</div>
Thanks!
If i understand you right, i think you could solve this with resolve.
First add a resolve function to your routing:
.when('productos/', {
templateUrl : 'pages/home/home.html',
controller : 'mainController',
resolve: {
anchorname: function() { {
// anchor name
return 'productos'
}
}
})
In your controller pass the resolve object and add some function for the scrolling
freddoApp.controller('mainController', function($scope, $location, $anchorScroll, anchorname) {
if(anchorname){
$location.hash(anchorname);
$anchorScroll();
}
})
This should immediately scroll to the anchor after you selecting the route.
EDIT: Its working, see here: https://jsfiddle.net/326f44xu/
Best approach for you is using routing url params like /home/:section. If you do it in that way, you are able to access from any other page. PLUNKER
ROUTE CONFIG
app.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/home/:section?', {
templateUrl: 'home.html',
controller: 'mainController'
}) //You don't need to repeat your .when() multiple times
$routeProvider.otherwise({
redirectTo: '/home'
});
});
HOME CTRL (mainController)
app.controller('mainController', function($routeParams, $location, $anchorScroll) {
//wrap this on $onInit or activate() function if you want
$location.hash($routeParams.section);
$anchorScroll();
});
HOME.HTML
<div><!-- HOME --></div>
<div id="productos"><!-- Productos--></div>
<div id="unico"><!-- unico--></div>
<div id="sabores"><!-- sabores--></div>
INDEX.HTML
<body>
<div>
<a ng-href="#/home">Home</a>
<a ng-href="#/home/productos">productos</a>
<a ng-href="#/home/unico">Unicos</a>
<a ng-href="#/home/sabores">Sabores</a>
</div>
<div ng-view></div>
</body>
** You can use empty route with optional params like /:section?, but I added /home to make it clear. The ? at the end of url param is to make it optional.

Login application - redirect to another page on click on submit button

When I am running index.html its opening but on clicking the submit button in login page I need it to redirect to another page such that validation happens in the redirected page and it displays something.
Suppose the login page opens with this url
http://localhost:51499/index.html
I enter credentials and click on submit button. I need it to redirect to another url to do the validations there and throw success message. Currently on clicking submit button is redirecting to a blank page but not the next url.
My angular code:
angular.module('Project', [])
.controller('loginCtrl', ['$scope', '$http','$location', function ($scope, $http) {
$scope.login = function (emailId, password) {
var uri = 'http://localhost:64367/api/Project/ValidateLogin/' + emailId + "/" + password;
$http.get(uri).then(function (data) {
if(data)
{
$location.path("/forgotpassword");
}
else {
alert("Error!!!");
//return;
}
});
}
}])
Route config code is here:
var mainApp = angular.module('Project', [ 'ngRoute']);
// configure our routes
mainApp.config(['$routeProvider',
function ($routeProvider) {
//In the above configuration, when user is idle for 900s (does not move mouse, press any key or button etc),
$routeProvider
// route for the login page
.when('/login', {
templateUrl: '../view/login.html',
controller: 'loginCtrl'
})
.when('/forgotpassword', {
templateUrl: '../view/ForgotPassword.html',
controller: 'forgotPasswordCtrl'
})
}]);
Error message:
You need create a new JS file for validatelogin controller and configure it with appropriate view(htmlpage1) same as login configuration.
.when('/login', {
templateUrl: '../view/login.html',
controller: 'loginCtrl'
})
.when('/validatelogin, {
templateUrl: '../view/HtmlPage1.html',
controller: 'validateloginCtrl'
})
also you need write this code
$location.path("/validatelogin") instead of $location.URL('http://localhost:51499/view/HtmlPage1.html');
Here is a sample article about this : Redirect to the original requested page after login using AngularJs

Show/Hide elements on website for certain pages

I am using AngularUI Router to navigate content on my website. I have some webpages that show the header/footer navigation and some that do not. I want to be able to detect what my current page is and insert the HTML for the header/footer if needed.
Here is my current router
angular.module('app', ['ui.router'])
.config(['$urlRouterProvider', '$stateProvider',
function($urlRouterProvider, $stateProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
templateUrl: 'partials/home.html',
controller: 'homeCtrl'
})
.state('about', {
url: '/about',
templateUrl: 'partials/about.html',
controller: 'aboutCtrl'
})
.state('contact', {
url: '/contact',
templateUrl: 'partials/contact.html',
controller: 'contactCtrl'
})
.state('create', {
url: '/create',
templateUrl: 'partials/create.html',
controller: 'createCtrl'
})
.state('login', {
url: '/login',
templateUrl: 'partials/login.html',
controller: 'loginCtrl'
})
}]);
For the html I have this
<html ng-app="app">
<body>
<!-- *********** HEADER ************* -->
<div ng-include=""></div>
<!-- ********** CONTENT *********** -->
<div ui-view></div>
<!-- **************** FOOTER ****************** -->
<div ng-include="'partials/standard_footer.html'"></div>
</body
</html>
For the webpages create and login I do not want to show the header and footer, but I am not sure how to do that.
I want to do something like this,
<div ng-if="!login && !create" ng-include="'standard_header.html'"></div>
How can I achieve this?
You can expose $state on the $rootScope and that will make it accessible in your webpage.
You can then simply check for state.current.name != 'login'
Like below:
Exposing the current state name with ui router
Edit:
Working Plunker of what i meant: https://plnkr.co/edit/JDpCo3fTePobuX9Qoxjn
You're almost there. Just add a flag in the params of the appropriate states:
.state('create', {
url: '/create',
templateUrl: 'partials/create.html',
controller: 'createCtrl',
params: {
hideHeaderAndFooter: true
}
})
.state('login', {
url: '/login',
templateUrl: 'partials/login.html',
controller: 'loginCtrl',
params: {
hideHeaderAndFooter: true
}
})
And then inject the $stateParams service in your controllers. Every property of the params object will be exposed as a property of the object this service returns:
loginCtrl.$inject = ['$scope', '$stateParams']
function loginCtrl($scope, $stateParams) {
$scope.hideHeaderAndFooter = $stateParams.hideHeaderAndFooter
}
Then you can use ng-if just the way you meant to use it:
<div ng-if="!hideHeaderAndFooter" ng-include="'standard_header.html'"></div>

Route Angular to New Controller after Login

I'm kind of stuck on how to route my angular app to a new controller after login. I have a simple app, that uses 'loginservice'... after logging in, it then routes to /home which has a different template from the index.html(login page).
I want to use /home as the route that displays the partial views of my flightforms controllers. What is the best way to configure my routes so that after login, /home is the default and the routes are called into that particular templates view. Seems easy but I keep getting the /login page when i click on a link which is suppose to pass the partial view into the default.html template:
var app= angular.module('myApp', ['ngRoute']);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/login', {
templateUrl: 'partials/login.html',
controller: 'loginCtrl'
});
$routeProvider.when('/home', {
templateUrl: 'partials/default.html',
controller: 'defaultCtrl'
});
}]);
flightforms.config(['$routeProvider', function($routeProvider){
//sub pages
$routeProvider.when('/home', {
templateUrl: 'partials/default.html',
controller: 'defaultCtrl'
});
$routeProvider.when('/status', {
templateUrl: 'partials/subpages/home.html',
controller: 'statusCtrl'
});
$routeProvider.when('/observer-ao', {
templateUrl: 'partials/subpages/aobsrv.html',
controller: 'obsvaoCtrl'
});
$routeProvider.when('/dispatch', {
templateUrl: 'partials/subpages/disp.html',
controller: 'dispatchCtrl'
});
$routeProvider.when('/fieldmgr', {
templateUrl: 'partials/subpages/fieldopmgr.html',
controller: 'fieldmgrCtrl'
});
$routeProvider.when('/obs-backoffice', {
templateUrl: 'partials/subpages/obsbkoff.html',
controller: 'obsbkoffCtrl'
});
$routeProvider.when('/add-user', {
templateUrl: 'partials/subpages/users.html',
controller: 'userCtrl'
});
$routeProvider.otherwise({
redirectTo: '/status'
});
}]);
app.run(function($rootScope, $location, loginService) {
var routespermission=['/home']; //route that require login
$rootScope.$on('$routeChangeStart', function(){
if( routespermission.indexOf($location.path()) !=-1)
{
var connected=loginService.islogged();
connected.then(function(msg) {
if(!msg.data) $location.path('/login');
});
}
});
});
and my controllers are simple. Here's a sample of what they look like:
var flightformsControllers = angular.module('flightformsController', []);
flightforms.controller('fieldmgrCtrl', ['$scope','$http','loginService',
function($scope,loginService) {
$scope.txt='You are logged in';
$scope.logout=function(){
loginService.logout();
}
}]);
Any ideas on how to get my partials to display in the /home default.html template would be appreciated.
1) Move all the routing into the main app.config, and remove the duplicate route for /home.
2) change this line
var flightformsControllers = angular.module('flightformsController', []);
to
var flightforms = angular.module('flightforms', []);
3) change the app definition line to inject the flightforms module:
var app= angular.module('myApp', ['ngRoute', 'flightforms']);
That should get ya close.
For one of your comments, its a good idea to have an interecptor which catches any 401 un-authenticated errors from the server. This way, if a user's session expires before a route change, they will still have to login again to start a new session. Something like this in app.config should do it.
$provide.factory('logoutOn401', ['$q', '$injector', function ($q, $injector) {
return {
'responseError': function(response) {
if (response.status === 401) {
$location.path('/login')
return $q.reject();
} else {
return $q.reject(response);
}
}
};
}]);
$httpProvider.interceptors.push('logoutOn401');

URL in web api and angularjs

in visual studio 2013 i have setup a web api project and added an index.html page with angularjs framework: why, when i run the project, the url is
http://localhost:49375/index.html#/
How can i remove the index.hmtl# for the root page?
In angularjs i have the following route:
gestionale.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'View/people.html',
controller: 'mainController'
});
}]);
and in the WebApiConfig.cs:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
I think you refer to:
$locationProvider.html5Mode(true);
It is use something like this:
angular.module('demoApp',['ngRoute'],function ($routeProvider, $locationProvider)
{
$locationProvider.html5Mode(true);
$routeProvider.
when('/',{
...
It basically lets you use angular routing without the # prefix character.