ui-router: Reset $state without using $state.go() - javascript

First off, I think the overall issue here is that AngularJS still doesn't have a sensible, best practice way of "restarting" the app and all its components. So far, the best practice seems to be setting the path to a "default" view, and then reloading the window. We do this in our /logout state, as seen here:
$stateProvider.state('logout', {
onEnter: function($state, $window, store) {
//Remove any session variables
store.remove('varA');
store.remove('varB');
//"Logout" the user
$state.go('login');
$window.location.reload();
}
})
However, this is a bad user experience. The user can actually see the view change and the components on the page shift before the window reloads. It just seems very buggy overall.
Originally, we did not include $state.go('login'), and did not get the weird experience of seeing the view change before logout. However, when we started using $state handlers like $rootScope.$on('$stateChangeStart', function (event, toState, toParams), we noticed that toState was not being reset after the window reload. So $stateChangeStart would trigger after the reload, and toState would still be set to whatever view the user was on before calling /logout. This isn't a true app reset!
Possible Solution: I think all of this can be solved if there was a way to "reset $state" without using the $state.go() method...something that happens behind the scenes instead.

Simple code change fixed it for me
//"Logout" the user
$state.go('login', null, {notify: false}).then(function() {
$window.location.reload();
});
Source: https://github.com/angular-ui/ui-router/issues/2486#issuecomment-180872463

Related

Prevent user to navigate away with unsaved changes

I'm currently using Backbone.Marionette to create a SPA and in one of the views it is possible for the user to navigate away with unsaved changes. I can control some of these events, like buttons and menu options within the view that would take the user away, but some others would require to manipulate either Backbone.Router or work with the DOM events directly.
I already tried listening to beforeunload (doesn't work as the application is still loaded) and hashchange (doesn't work as you cannot stop the browser from navigating away). These solutions (1, 2, 3) don't work in this case, the Javascript is never unloaded.
Changing the Backbone.Router seems to be the best option, but because of how it is initialized I don't think it is possible to introduce this feature or at least I cannot find a way of doing it. This solution, for example, doesn't work because hashchange is not cancelable (you cannot call stopPropagation on it), and this other solution doesn't work because navigate is not defined on the Backbone.Router object.
Any suggestions?
I've managed to find a solution to this, although some more work is required. For this solution, I am assuming that you keep track when a view is dirty.
There are 4 main ways of moving out of a view;
Click on a link on the view
Click on link outside the view
Click on refresh or external link
Click on back/forward on the browser
1. Application link
This is the easiest case. When you click on your own link, you have to check if your view is dirty. For example, I have an in-app back button that is handled by a historyBack function. On the view:
historyBack: function() {
if (this.isDirty) {
answer = confirm("There are unsaved changes.\n\nDo you wish to continue?")
if (answer) {
this.isDirty = false
window.history.back()
}
}
else {
window.history.back()
}
}
2. Links outside your view
This type of interaction can be handled by extending the Router prototype's execute method, not the navigate method as proposed in other places.
There should be a variable somewhere accessible by the Router that stores the state of the view. In my case, I'm using the Router itself and I update this variable every time I change the dirty flag on the view.
The code should look something like this:
_.extend(Backbone.Router.prototype, {
execute: function (callback, args, name) {
if (Backbone.Router.isDirty) {
answer = confirm "There are unsaved changes.\n\nDo you wish to continue?";
if (!answer) {
return false;
}
}
Backbone.Router.isDirty = false
if (callback) callback.apply(this, args)
}
}
3. Refresh or external link
Refresh and external links actually unload your Javascript so here the solutions based on beforeunload (see question) actually work. Wherever you manage your view, I use a controller but let's assume it's on the same view, you add a listener on show and remove it on destroy:
onShow: function() {
$(window).bind("beforeunload", function (e) {
if (this.isDirty) {
return "There are unsaved changes.";
}
}
}
onDestroy: function() {
$(window).unbind("beforeunload");
}
4. Back/Forward on the browser
This is the trickiest case and the one I haven't figured out completely yet. When hitting back/forward, the user can navigate out of the app or within the app, both cases are covered by the code on 1 and 3, but there is an issue I can't figure out and I will create another question for it.
When hitting back/forward, the browser changes the address bar before calling the router so you end up with an inconsistent state: The address bar shows a different route to the application state. This is a big issue, if the user clicks again on the back button, after saving or discarding the changes, she will be taken to another route, not the previous one.
Everything else works fine, it shows a pop up asking the user if she wants to leave or continue and doesn't reload the view if the user chooses to stay.

AngularJS with ui.router: reload page when clicking the same state link

I just got a request from our QA team, which I think sounds ridiculous. Here it goes: suppose you are already on the 'about' state/page in the angular-based app, and when you click on the 'about' state url again from the top menu, you want the 'about' page to reload. The about page does not fetch data from anywhere, by the way, a reload is simply equivalent to a blink.
For the state config in my angular app is like this:
.state('about', {
url: '/about',
templateUrl: '/path/to/about.html',
controller: 'aboutCtrl as aboutView'
});
And in the top menus, we have a link pointing to this state:
<a ui-sref="about">About</a>
I have tried many things to get this to work: clicking the link triggers the reload of the same state.
Things like $state.go('about', {}, {reload: true}); or $state.transitionTo('about', {}, {reload: true}); don't work, because the links are static.
One last resort I am currently trying is to manipulate the reload thing in the run phase of Angular by listening to '$stateChangeSuccess' event, but I don't think it will work, because there's no state change at all if you click on the 'about' link while you are right on that state.
Is there any ways to work around this? Thanks
There is an option attribute called ui-sref-opts that comes with the UI Router. I faced the same problem and it solved it.
Eg: <a ui-sref="home" ui-sref-opts="{reload: true}">Home</a>
Docs URL : UI Router DOcs
You're right, I can't get any state change events to fire either once already in that state. Until, and if that functionality becomes available to use through that api someday, here's a semi-hacky solution for this. We can just leverage ng-click and use some silly logic to appease QA (in your case). Also, I don't know your controller implementation, so I placed my suggestion on $rootScope in .run in this example for simplicity and visibility, but integrate accordingly if you choose to do so. Observe the following example...
<a ui-sref="about" ng-click="sillyQA()">About</a>
.run(['$rootScope', '$state', function($rootScope, $state) {
$rootScope.sillyQA = function() {
if($state.current.name === 'about') {
$state.go('about', {}, { reload: true });
}
}
// -- just to see our about => about state 'change'
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){
console.log('toState: ' + toState.name );
console.log('fromState: ' + (fromState.name || 'Just got there! click again!'));
})
}]);
JSFiddle Link - demo

Remove / cancel animations in ui router when navigating back and forth

I'm using AngularJS ui router and I have about 3 pages in total. The problem I am facing is that on the home page (first page) I have an intro animation which lasts about 10 seconds in total. The intro animation is attached to the directive.
Now once I land on that page, the intro starts and everything is fine until I navigate to another page - it seems that the intro keeps playing as if the DOM and in particular - the directive was not removed properly.
Is there a way to remove / clear DOM before navigating to another page?
The code is massive to post here and I was wondering if there is a quick fix for this? If not, I will try to post it on jsfiddle.
Mabe something like this will help
.run(function($rootScope, $route, $location) {
$rootScope.$on("$stateChangeStart", function (ev, to, toParams, from, fromParams) { {
//to.name is new state name
//from.name is old state name
TweenMax.killTweensOf($("#yourId"));
});
});

$state.go doesn’t redirect to given path

i've got a view that's outside of my tabs, now when i try to redirect from that view to a tab i get redirected to the wrong tab. i've made a codepen to show you what i mean since i don't really know how to explain it well see the logs i create in the console
.controller('MyCtrl', function($scope, $state, $rootScope, $ionicPlatform) {
$rootScope.$on('$stateChangeStart',function(event, toState, toParams, fromState, fromParams){
// do something
$scope.from = fromState;
console.log(fromState);
})
$scope.goBack = function(){
console.log($scope.from.name);
$state.go($scope.from.name);
}
})
Codepen
You should apply the other answers but you have another problem.
The other problem is that, when you click on back button the state is changing to tab.volgend (which is right) but after this is going to tab.alert state... so I'm trying to figure out why is this second redirect happening.
Extract from console.log when clicking back button:
My first candidate is:
$urlRouterProvider.otherwise('/tab/alerts');
You shouldn't use ui-route with standard routing, so you should comment this line an add the next in your controller:
console.log('going to default state');
$state.go('tab.alerts');
EDIT
The second transition is made by the ionic framework, I have put a breakpoint and check the callstack, check this captures:
1- first call when back is clicked:
2- The ionic framework detects a change in the url and.. fires the second transition:
I'm going to read more this framework to see if I understand why is this happening... I keep you updated.
You should pass the name of the state to $state.go(), not the state object.
So $state.go($scope.from.name) should solve this for you.
why not simply use
$state.go('stateName', {//for stateParams}, { reload: true });
This happened with me too. Try transitionTo method, instead of go
$state.transitionTo($scope.from.name);
This worked out in my case.
More details can be found here
Edit : I forked your original codepen and it worked there too.. Forked Codepen here

AngularJS $stateParams when using reloadOnSearch:false

I have a page in my application which uses a search so i have added the "realoadOnSearch:false" which works perfectly
The problem I have is when navigating to the same state with a different stateParam:
when I navigate to #/category/20/ from any other page it works fine... i then have a link on that page to #/category/3 (the parent category for 20) and the URL updates, however the content does not (no console errors)
app.js (main application)
.state('category', {
url: '/category/:categoryId/',
templateUrl: '/Home/Category',
controller: 'categoryCtrl',
reloadOnSearch: false
})
I have tried adding target="_self" to force page reload and it does not work
I have also tried to watch $stateParams for changes and there is nothing
Clicking the link to #/category/3 from #/category/20 (and vice versa) should navigate to the new page and reload the data, where search should NOT reload the page (latter works but not the former)
The URL is prefered to be a ng-href rather than ng-click as it is managed by the root controller
EDIT:
I did not find a direct solution, however i just disabled the reloadOnSearch and my sorting buttons still work so this works for me for now as a solution.
The problem is that reloadOnSearch doesn't do what you think it does; it's actually more like reloadOnStateParams. Setting it to false prevents you from making state changes where only the stateParams change, which is what you're doing here (going from #/category/3 to #/category/20).
You can see this documented on the UI router issues page: https://github.com/angular-ui/ui-router/issues/1079
There's some workarounds in there but none of them are great. You are probably best off using an ng-click that forces a reload manually, something like this:
$state.transitionTo($state.current, $stateParams, {
reload: true,
inherit: false,
notify: true
});

Categories

Resources