I'm using angular-ui-router with HTML5 mode set to false - I use hashbang. When user hits mydomain.com I need to redirect him to mydomain.com/#/welcome, how can I do that?
I've looked through ui-router source code and when mydomain.com is hit the $location.path() is "" so this approach .when("", "/welcome") doesn't work since .when("" translates into this /^$/ regex and when "" is tested against this regex null is returned.
This seems to be a viable solution:
appModule.run(['$location', function ($location) {
if ($location.path() === "") {
$location.path("/");
}
Use $urlRouterProvider.otherwise to redirect to your welcome page if the current URL doesn't match any of your states.
$urlRouterProvider.otherwise('/welcome');
See this stack overflow question: Otherwise on StateProvider
If you just want to show welcome.html you can do something like below
.when('/', {
templateUrl: 'welcome.html',
controller: 'homeCtrl'
})
Else if you want to redirect user to mydomain.com/#/welcome you can use window.locations or you can handle it as the part of homeCtrl where you can redirect it using $location.path('/welcome'); and below be route for it
.when('/welcome', {
templateUrl: 'welcome.html',
controller: 'welcomeCtrl'
})
Related
Hi guys am a beginner in mean stack development I have tried to refresh the page after logout.I have tried location.reload(); but it doesn't work tell me the possible code for page reload in this scenario
$rootScope.$on('$routeChangeStart', function (event) {
var storage = userService.isLoggedIn();
console.log(storage);
if (!storage) {
console.log('DENY');
$rootScope.adminlogin = "adminlogin";
console.log($rootScope.adminlogin);
$location.path('/login');
$route.reload();
// $state.go('/login', null, {reload: true});
}
else {
console.log('ALLOW');
$rootScope.admindashboard = "admindashboard";
var path = $location.path();
console.log(path);
console.log(storage);
if(path == '/login'){
$location.path('/');
}
}
});
You should use $window.location.reload() from the the $window service if you want to refresh the page. It does the same thing as the reload button in your browser.
The reason you should use the $window service instead of directly accessing the native window object as per the AngularJS documentation:
While window is globally available in JavaScript, it causes
testability problems, because it is a global variable. In AngularJS we
always refer to it through the $window service, so it may be
overridden, removed or mocked for testing.
On a side note as you stated you are using the $route service, just calling $route.reload() will only reload your controllers and not your entire application.
All you need to do is this little line of Vanilia JS:
document.location.href=document.location.href
EDIT: why is this getting downvoted?
if you are using routes, then on click of Logout just route it to your login page.
Snap shot from demo:
these are my routes:
$routeProvider
.when('/login', {
controller: 'LoginController',
templateUrl: 'modules/authentication/views/login.html',
hideMenus: true
})
.when('/', {
controller: 'HomeController',
templateUrl: 'modules/home/views/home.html'
})
.otherwise({ redirectTo: '/login' });
and when i click on 'Logout' on my page it should do somehting like:
<p>Logout</a></p>
it should redirect to login page as per routes.
I am building a simple HTML site using Angular JS ui-router.
I have built a custom 404 page ('www.mysite/#/error/404'), to which the user is redirected if the user types a url like 'www.mysite/#/invalidUrl'. This functionality was achieved by the following code snippet:
$urlRouterProvider
.when('', '/')
.when('/home', '/')
.otherwise('/error/404');
And the following state snippet:
$stateProvider.state('404', {
parent: 'app',
url: '^/error/404',
views: {
'errorContent#main': {
controller: 'error404Controller',
templateUrl: 'js/general/templates/error404.html'
}
}
});
I am trying to capture the invalid URL requested by the user to be displayed to the user like below.
The URL you requested cannot be found
Request: www.mysite.com/#/invalidUrl
I have tried listening to '$stateNotFound' event, which only seems to be firing when a specific invalid state is requested. I've also tried to listening to events '$stateChangeStart', '$locationChangeStart', and '$locationChangeSuccess' but couldn't find a way to achieve this functionality.
Is this possible? Please, share your thoughts - thank you
Awesome! Thank you Radim Köhler. I don't know how I didn't land on that thread when I searched but that helped me get the answer.
I changed the answer in that thread to fit my scenario which I am going to leave below for reference to any other users.
$stateProvider.state('404', {
parent: 'app',
url: '^/error/404',
views: {
'errorContent#main': {
controller: 'error404Controller',
templateUrl: 'js/general/templates/error404.html'
}
}
});
$urlRouterProvider
.when('', '/')
.when('/home', '/')
.otherwise(function ($injector, $location) {
var state = $injector.get('$state');
state.go('404', { url: $location.path() }, { location: true });
});
So the magic change was the function defined for 'otherwise' option. I didn't change the URL of the 'error' state. Instead, I used the 'state.go' to activate state '404' and passed the location path as the state parameter.
Setting location=true will take you to the URL of the state, and location=false will not. Whichever way you prefer the invalid URL can be accessed easily now.
it's probably a rookie mistake but I am having trouble changing my page using:
$state.go('login');
My routing looks as following:
$stateProvider
.state('login', {
url: "/login",
templateUrl: "./auth/login.html",
controller: 'loginCtrl'
})
I also added a
$rootScope.$on("$stateChangeStart", function (event, next) {...}
just to check if it gets there after I use $state.go() and yes; it gets there but it does not change my page or URL at all. Changing the page works fine with ui-sref="login" inside a view.html.
Other syntaxes I tried:
$state.go('login', null, {options: { location : true } } );
$state.go('login', {}, {location : true});
Btw, what I am trying to accomplish is redirecting to a login-page when the user is not authorized inside the $stageChangeStart-event.
Any ideas?
Visit Angular ui router - Redirection doesn't work at all . It gave me a more clear idea of what I was doing wrong.
The actual solution for me was found at the following page answered by frankwallis:
https://github.com/angular-ui/ui-router/issues/600
I replaced my default $urlRouterProvider.otherwise('/yourpage'); with
$urlRouterProvider.otherwise( function($injector, $location) {
var $state = $injector.get("$state");
$state.go("app.home");
});
Too bad I don't really understand the solution but atleast it works now!
i want create a route for angularJs which will be accessible only from application code and links. The main idea is to prevent the user to access the page after directly typing route url in browser's location bar.
For route configuration i use "ngRoute" module's $routeProvider.
I can't find an answer for this question. Is the thing i need possible?
Thanks in advance.
You can listen $locationChangeStart event. In your routes you can set a parameter (I've called it "restricted" but you could call it whatever you want) like this:
app.config(function($routeProvider) {
$routeProvider
.when('/', {
controller: 'MainCtrl',
template: 'Allowed from anywhere.<br>Go to main page',
restricted: false
})
.when('/main', {
controller: 'MainCtrl',
template: 'Allowed from anywhere.<br>Go to restricted page',
restricted: false
}).when('/restr', {
controller: 'RestrictedPageCtrl',
template: 'Allowed only from main',
restricted: '/main'
});
});
If it's false, that means there's no restriction, if it's set to a path, then the route is only accessible from that path. And you can check it with this:
app.run(function($rootScope, $location, $route) {
$rootScope.$on('$locationChangeStart', function(event, next, current) {
var nextRoute = $route.routes[$location.path()];
var currentPath = current.split('#')[1];
if (nextRoute.restricted && nextRoute.restricted !== currentPath) {
$location.path('/');
alert('You are trying to reach a restricted page!!!!');
}
});
});
You can change the behaviour and redirect user to another link or prevent location change with event.preventDefault();.
Note that if you are not using hashtag (#) in your links (html5Mode) you should change the way to get the current link.
Here's a plunker.
If the user has become logged out, I want to send the user to the login page, but it fails. I have this configuration:
webShopApp.config(function($routeProvider) {
$routeProvider.when('/login', {
templateUrl: 'partials/login.html',
controller: 'LoginController'
});
$routeProvider.when('/:id?/?products', {
templateUrl: 'partials/products.html',
controller: 'MenuController'
});
});
Note the "/:id?/?" inte the code for products. Let's say the url is 'index.html#/45/products'. If the controller discovers that the user is logged out, it calls
$location.path('/login');
If I console.log the $location.path(), it says '/login' as expected, but the url in the browser is 'index.html#/45/login'. Why is the '45' (the id) still there, and how do I get rid of it, ie, redirect to 'index.html#/login' without the id from the previous path?
I guess you should use window.location = 'yourUrl'; instead of $location.path('/login'); in this case. But in this case, the page is reloaded.
see if you need to workout in pure angularjs, so please avoid javascript terms and jquery terms i.e. windows.location and $location.path; Better option is always to route the user to login page whenever the user gets logout from the App.
for this you can specify it at the routing level i.e.
$routeProvider.otherwise({redirectTo: "/login"});
or you can say a logout link on clicking of which user will be redirected to login page
$routeProvider.when('/logout', {
templateUrl: 'partials/login.html',
controller: 'LoginController'
});
I hope this may help.