UI-router : $state.current.name shows empty - angularjs

Sometimes state which i define is not render and shows blank page.
And at this time when i try to see from console which state is this, it shows like below.
state name shows empty, which is not defined in my app.
Anybody know about this issue please help me.

I am guessing you see the full object in console because it gets filled later and the browser reacts..
Try to include your block with $state into a $timeout(). It's a trick to wait for the $digest cycle to be over before getting the value.
$timeout(function() { console.log($state.current.name); });
or
$rootScope.$on('$stateChangeSuccess',
function(event, toState, toParams, fromState, fromParams) {
var statename = toState.name
console.log(statename) })

Related

Change the URL breaks the routing prevent

I have a requirement to prevent routing if it is first time login user, they have to stay in the setting page to reset password before do something else (or go to other pages), the code is 99% working now, I can change the url/ refresh page, it works fine but only one issue. Here is code:
.state('accountsetting.security', {
url: '/security/{isFirstTimeUser}',
templateUrl: 'settings/security/security.html',
params: {'isFirstTimeUser': null}
}) // this is where I define the route
// in the run block
.run(['$state','$rootScope',function($state,$rootScope) {
// var isFirstTimeUser = false;
// userinforservice.getUserInformation().then(function(data){
// isFirstTimeUser = data.isFirstTimeUser;
// });
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
if(fromState.name!=="undefined" && toState.name=='firsttimeuser'){
$rootScope.isFirstTimeUser=true;
$state.go('accountsetting.security',{isFirstTimeUser:true});
event.preventDefault();
}else if((toParams.isFirstTimeUser || fromParams.isFirstTimeUser) && toState.name !='accountsetting.security'){
$state.go('accountsetting.security',{isFirstTimeUser:true});
event.preventDefault();
}
else{
return;
}
});
}]);
The url is like: https://localhost/app/#/account/security/true
As I mentioned, I can refresh the page or change the url like:https://localhost/app/#/account or https://localhost/app/#
they all work fine, but when I change the url like this:
https://localhost/app/ it will take me to the home page. I check console, in the statechangestart, I lost the isFirstTimeUser, it is undefind. any idea about it?
Thanks in advance.
You lose angular state when you go to the url of the root rather than the state url (i.e) #(hash) urls. The root url reloads the page wherein you lose memory of all javascript variables as they are all client side. Hence the variable is undefined.
State changes happen in a single instance of page load, the url changes give you a illusion as if a page load is happening
The issue causing this behaviour is described by Shintus answer.
A possible solution would be to make sure the event order is correctly resolved. I assume $stateChangeStart is fired before userinforservice.getUserInformation() is resolved. Instead of calling them in parallel you could query the returned promise inside your $stateChangeStart instead of the variable assigned at any undefined time.
.run(['$state','$rootScope',function($state,$rootScope) {
var storedUserPromise;
storedUserPromise = userinfoservice.getUserInformation();
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
storedUserPromise.then(function(data) {
if(data.isFirstTimeUser) {
//do redirection logic here
}
})
});
}]);
Storing the user promise allows you to only have the overhead of calling userinfoservice.getUserInformation() once. Afterwards any .then on the stored promise resolves instantly.
PS: you probably have a typo in userinfo>r<service ;)
You can intercept any route loading in your route definition with $routeProvider.when.resolve, check their status in the resolve block and redirect them or anything else you want to do.
Tutorial Example showing the below code snippet:
$routeProvider
.when("/news", {
templateUrl: "newsView.html",
controller: "newsController",
resolve: {
message: function(messageService){
return messageService.getMessage();
}
}
})

Run a function every time an angular route is navigated to

I want to run a function every time an Angular route is navigated to.
One option is I just add myFunction() to the top of every controller. Seems really repetitive. Is there a better way to run myFunction() every time $location changes?
If you are using ui-router, you can simply bind a function to the $rootscope.
See the stateChange section: https://github.com/angular-ui/ui-router/wiki#state-change-events
$rootScope.$on('$stateChangeSuccess',
function(event, toState, toParams, fromState, fromParams){ ... })

How can I bring up an "in progress" loading bar in between ui-router state transitions?

I have an AngularJS application that uses ui-router. There are times when the application waits while moving from one state to another and while the resolves are still in progress.
Does anyone have (or have they seen) any examples of how I can present an "in-progress" loading bar on the screen just during the time of the resolve from the one state to another?
You can use the events emitted by ui-router (as well as the native routeProvider).
Plunker
Something like this:
$rootScope.$on('$stateChangeStart',
function(event, toState, toParams, fromState, fromParams){
$rootScope.stateIsLoading = true;
})
$rootScope.$on('$stateChangeSuccess',
function(event, toState, toParams, fromState, fromParams){
$rootScope.stateIsLoading = false;
})
Then in HTML:
<section ui-view ng-hide="stateIsLoading"></section>
<div class="loader" ng-show="stateIsLoading"></div>
docs
You can use resolve to provide your controller with content or data
that is custom to the state. resolve is an optional map of
dependencies which should be injected into the controller.
If any of these dependencies are promises, they will be resolved and
converted to a value before the controller is instantiated and the
$stateChangeSuccess event is fired.

UI- Router -- run function on every route change -- where does the state name live?

Using Angularjs and UI-Router, trying to run a function every time state changes
$rootScope.$on('$stateChangeStart',
function(toState){
if(toState !== 'login')
UsersService.redirect();
})
I put this in .run() and i can successfully log out toState every time route changes. However, i can't seem to find the property which has the name of the state that we are going to. If someone can tell me where to find that, i think i should be in good shape.
Ended up with this and it does what i want.
$rootScope.$on('$stateChangeStart',
function(event, toState, toParams, fromState, fromParams){
if(toState.name !== 'login' && !UsersService.getCurrentUser()) {
event.preventDefault();
$state.go('login');
}
});

Can't get $anchorScroll working on $stateChangeSuccess?

I'm trying to adapt the answer give in this similar question How to handle anchor hash linking in AngularJS. I need to be able to use it with ui-router. I've tested anchor scrolling as a clickable function in my controller and that is working. Here is the code for that
$scope.anchor = function () {
console.log('test');
$location.hash('comments');
$anchorScroll();
};
If I try to invoke that function immediately nothing happens
$scope.anchor();
If I try to invoke it on a $stateChangeSuccess nothing happens. I threw in a log for sanity and that is firing. I also tried a trick to prevent further routing logic from kicking in. It was mentioned in the linked post but I'm not sure if it's necessary for my case.
app.run(function ($rootScope, $location, $stateParams, $anchorScroll) {
// allow anchorScrolling
$rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
console.log('stateChangeSuccess');
var old = $location.hash();
$location.hash('comments');
$anchorScroll();
//reset to old to keep any additional routing logic from kicking in
$location.hash(old);
});
});
I'm guessing that I'm running into race conditions or my anchor scroll is somehow triggering another route change. But I can't figure out how to track these issues down. Any thoughts?
EDIT: Update I removed the $location.hash(old); and put the rest of the $anchorScroll pieces into a timeout function and it's now working. I also added in the $stateParams.scrollTo to make this useable with query params. Any ideas as to what is causing my race condition and how this might be solved without a $timeout function?
$rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
console.log('stateChangeSuccess');
$timeout(function() {
$location.hash($stateParams.scrollTo);
$anchorScroll();
}, 300);
});
From $anchorScroll documentation
It also watches the $location.hash() and scrolls whenever it changes to match any anchor. This can be disabled by calling $anchorScrollProvider.disableAutoScrolling().
Try removing $location.hash(old);
If that fixes it, use $anchorScrollProvider.disableAutoScrolling() to disable it reacting to another state change.

Resources