DeepStateRedirect in angular ui-router 1 - how to reset the deep state? - angularjs

I'm using angularJS and migrating to ui-router v1. I'm trying to get deep state redirects working like they used to in the previous version of ui-router.
I've successfully implemented the DSRPlugin in my config modules, and deep state redirects are firing and work as expected. However, I'm unable to reset the deep state. I need to be able to reset the deep state on a button click, which means logic within my component. Previously I could inject $deepStateRedirect into my controllers and simply call $deepStateRedirect.reset({}), but I'm no longer able to inject $deepStateRedirect. How can I access the reset method in ui-router v 1?
I have also noticed that when using DSR as a config object you can specify a function to determine if the redirect occurs. I could alternatively use this to determine whether to do the redirect or not, but the documentation is lacking. It shows that I should return a truthy value to do the redirect or a falsey value to prevent the redirect. In testing, returning true or false only causes a transition error: "i.state is not a function".
I'm not using a build process, just plain script includes.
Anyone have any ideas on how to make this work through either of the above methods?

This may not be the best practice way of doing the reset, but I found a solution after logging out various ui-router objects.
Inside of your controller you must inject the $uiRouter object. Then, you can set a variable to $uiRouter._plugins["deep-state-redirect"]. The reset() and other methods are available on the plugin's prototype.
You can then use that object and call those methods similar to how it worked in the previous version when injecting $deepStateRedirect.
var $deepStateRedirect = $uiRouter._plugins["deep-state-redirect"];
$deepStateRedirect.reset({});

I found this only in the source code and then in the documentation: https://ui-router.github.io/ng1/docs/latest/classes/core.uirouter.html#getplugin
The more correct way is to use UIRouter#getPlugin(pluginName), that is
var $deepStateRedirect = $uiRouter.getPlugin('deep-state-redirect');
$deepStateRedirect.reset(...);

Related

Angular UI Router - any way of referencing the same url variable more than once?

I would like to implement finite netsing of ui router states (it is required by the client), the maximum depth of nesting can be a fixed value (for example 10) therefore i would like my states to look as such:
.state('page',{url:'page/{pageName}',templateUrl:...)
.state('page.page',{url:'/{pageName}',templateUrl:...)
.state('page.page.page',url:'/{pageName},templateUrl:...)
etc...
In the end i would like for user to be able to enter urls like:
'/page/page1/subpage1'
'/page/page2/subpage1/subsubpage2'
'/page/page3'
etc...
The obvious problem is that ui router will overwrite the 'pageName' variable for each (sub)state, therefore after navigating to /page/page1/subpage1 i will only have {pageName:'subppage1'} variable set in state 'page' and 'page.page'.
In the whole application the ui-sref would only use the RELATIVE states so when i am in the 'page' state i would go into 'page.page' state and so on. I would like to be able to move the html view of the page up or down the state hierarchy as needed, and i would like not to change every ui-sref call in such case (right now i would have to change the variable name because it has to have different name in every state)
Is there any possibility to achieve my desired scenario? i have tried defining 'pageName' as an array type, but it does not seem to work (gets overwriten for every substate). Using custom ui router type also seems to not work since it cannot modify stateParams objects, only returns the representation of single url value (therefore the 'pageName' is also overwritten).
Ui-router extras also seems not to help here, or maybe i am missing something.

Prevent deep link in react-router

In my application I'd like to have certain portions of the app not be able to deep linked to. For example our users have a list of surveys and I'd like if someone tried to go directly to a particular survey directly such as /survey/1 that react router would pick up on this and immediately redirect them back to /survey and they would have to select the one they want. I've tried to write onEnter hooks but they seem to be very cumbersome since the only way I've been able to get them to behave correctly is to store some global state that says they have been to the main page and inspect that every time the route is navigated to.
Im using pushstate in my application if that makes any difference and react-router 2.0
I'd like to try to avoid having to write server rewrite rules for this since there are a lot of areas in my application where this rule is applicable.
I have a suggestion which is similar to the onEnter hook:
Wrap the component of the survey/:id route with a function which verifies if deep linking is allowed or not, let's call this function preventDeepLinking
The preventDeepLinking function checks if the location state contains a certain flag, let's say allowDeep. This flag would be set in the location state when navigating from another page of your app. Obviously, this flag will not be set when the user tries to navigate directly to the page of a survey.
The preventDeepLinking function will render the wrapped component only if deep linking is allowed, otherwise will redirect to a higher route.
I created a sample on codepen.io. You can play with it in the debug view of the Pen: http://s.codepen.io/alexchiri/debug/GZoRze.
In the debug view, click the Users link and then on a specific user from the list. Its name will be displayed below. Notice that its id is part of the url. Remove the hash including the ?_ and hit Enter. You will be redirected to /users.
The code of the Pen is here: http://codepen.io/alexchiri/pen/GZoRze
The preventDeepLinking function can be improved, but this is just to prove a point. Also, I would use the browserHistory in react-router but for some reason I couldn't get it running in codepen.
Hope this helps.

Check if url leads to a defined state in AngularJS

I use UI-Router and if the requested state doesn't exist in my config I want the app go to a certain state depending on whether the user is authenticated or not. Either 'home' or 'dashboard'.
I tried to use $urlRouterProvider.otherwise but the authenticated is not available there (in app.config). Then I tried in app.run to use 'stateChangeError' and 'stateNotFound' which interestingly have no effect at all here.
So my idea to work around this is to check if the state exists by using the URL - which I can get with $location.path(). But a $state.get() with this always delivers null because it expects the name of a state, not the URL.
So how can I find out, based on what the user enters, whether there is an according state?

Set URL query parameters without state change using Angular ui-router

How should I update the address bar URL with a changing query parameter using AngularJS' ui-router to maintain state when refreshing the page?
Currently, I am using $state.transitionTo('search', {q: 'updated search term'}) whenever input changes, but the problem is that this reloads the controller, redraws the window and loses any text input focus.
Is there a way to update stateParams and sync it to the window URL?
I was having trouble with .transitionTo until I updated to ui-router 0.2.14. 0.2.14 properly changes the location bar (without reloading the controller) using a call like this:
$state.transitionTo('search', {q: 'updated search term'}, { notify: false });
edit: Played around with this some more today, and realized that angular ui-router has a similar option as the native routerProvider: "reloadOnSearch".
https://github.com/angular-ui/ui-router/wiki/Quick-Reference#options-1
It's set to true by default, but if you set it to false on your state, then the state change won't happen when the query parameters are changed. You can then call $location.search(params); or $location.search('param', value); and the URL will change, but ui-router won't re-build the entire controller/view. You'll probably also need to listen for the $locationChangeStart event on the root scope to handle back and forward history actions within your app, as these also won't cause state changes.
I'm also listening for the $stateChangeSuccess event on my controller's scope to capture the initial load of the page/route.
There is some discussion on github for using this feature with path changes (not just URL changes): https://github.com/angular-ui/ui-router/issues/125 but I haven't tested that at all since my use case was specific to query string parameters.
The previous version of my answer mentioned this github issue:
https://github.com/angular-ui/ui-router/issues/562
But that's a slightly separate issue, specifically showing a modal of one state over another state without the non-modal state changing. I tried the patch in that issue, but it's clear that it isn't meant for preventing the entire state from reloading on URL change.
Update May 19, 2015
As of ui-router 0.2.15, the issue of reloading the state on query parameter changes has been resolved. However, the new update broke the history API back and forward capabilities with query parameters. I have not been able to find a workaround for that.
Original
Jay's answer didn't work for me, and neither did a ton of other answers. Trying to listen to $locationChangeStart caused problems when trying to go back and forth in the browser history as it would cause me to run code twice: once when the new state changed and another because $loationChangeStart fired.
I tried using reloadOnSearch=false, but that prevented state changes even when the url path changed. So I finally got it to work by doing the following:
When you change $location.search() to update the query parameters, use a "hack" to temporarily disable reloading on search, set query parameters, then re-enable reloading.
$state.current.reloadOnSearch = false;
$location.search('query', [1,2]);
$timeout(function () {
$state.current.reloadOnSearch = undefined;
});
This will ensure that query parameter changes do not reload the state and that url path changes will reload the state properly.
However, this didn't get the browsers history to change the state (needed for knowing when a query parameter changes to re-read the URL) when a query parameter was part of the url. So I also had to add each query parameter's name to the url property of the state.
$locationProvider.html5Mode(true);
$stateProvider
.state('home', {
url: '/?param1&param2&param3',
templateUrl: 'home.html',
controller: 'homeCtrl as home',
});
Any parameter names on the url are optional when listed this way, but any changes to those parameter names will reload the state when hitting the back and forward buttons on the browser.
Hopefully others find this useful and it doesn't take them multiple days to figure out how to do it (like I did).

Why is it considered bad practice to call trigger: true in the navigate function of backbone.js?

I have read in several places that calling the Backbone.history.navigate function is considered bad practice.
For example Addy Osmani sais in his book "Developing Backbone.js Applications"
It is also possible for Router.navigate() to trigger the route along
with updating the URL fragment by passing the trigger:true option.
Note: This usage is discouraged...
http://addyosmani.github.io/backbone-fundamentals/#backbone.history
Or Derick Bailey in his blog post even sais:
You shouldn’t be executing the route’s handler from within your application, most of the time.
But I don't really understand the reasoning behind it and what would be a better solution.
In my opinion it is not really bad to call the navigate function with the trigger:true option. The route function could upon calling always check if the considered data is already loaded and show this loaded data instead of doing the whole work all over again...
There seems to be some confusion about what Router#navigate does exactly, I think.
Without any options set it will update the URL to the fragment provided.
E.g. router.navigate('todo/4/edit') will update the URL to #todo/4 AND will create a browser history entry for that URL. No route handlers are run.
However, setting trigger:true will update the URL, but it will also run the handler that was specified for that route (In Addy's example it will call the routers editTodo function) and create a browser history entry.
When passing replace:true the url will be updated, no handler will be called, but it will NOT create a browser history entry.
Then, what I think the answer is:
the reason why the usage of trigger:true is discouraged is simple, navigating from application state to application state to application state requires most of the time different code to be run than when navigating to a specific application state directly.
Let's say you have states A, B and C in your application. But state B builds upon state A and state C builds upon B.
In that case when you navigate from B to C only a specific part of code will need to be executed, while when hitting state C directly will probably execute some state checking and preparation:
has that data been loaded? If not, load it.
is the user logged in? If not redirect.
etc.
Let's take an example: State A (#list) shows a list of songs. State B (#login) is about user authentication and state C (#list/edit) allows for editing of the list of songs.
So, when the user lands on state A the list of songs is loaded and stored in a collection. He clicks on a login-button and is redirected to a login form. He successfully authenticates and is redirected back to the song list, but this time with delete-buttons next to the songs.
He bookmarks the last state (#list/edit).
Now, what needs to happen when the user clicks on the bookmark a few days later?
The application needs to load the songs, needs to verify the user is (still) logged in and react accordingly, stuff that in the state transition flow had already been done in the other states.
Now for a note of my own:
I'd never recommend the above approach in a real application as in the example. You should check whether the collection is loaded when going from B to C and not just assume it already is. Likewise you should check whether the user really is logged in. It's just an example.
IMO the router really is a special kind of view (think about it, it displays application state and translates user input into application state/events) and should always be treated as such. You should never ever rely on the router to transition between states, but rather let the router reflect the state transitions.
I have to disagree with #Stephen's answer here. And the main reason why is because the use of router.navigate({trigger : true}) gives the router responsibility to handle the application's state. It should only reflect application state, not control it.
Also, it is not a View's responsibility to change the hash of the window, this is the router's only job! Don't take it away from it! Good modularity and separation of concerns makes for a scalable and maintainable application.
Forwarding a person to a new section within your application
Backbone is an event driven framework, use events to communicate. There is absolutely no need to call router.navigate({ trigger : true }) since functionality should not be in the router. Here is an example of how I use the router and I think promotes good modularity and separation of concerns.
var Router = Backbone.Router.extend({
initialize: function(app) {
this.app = app;
},
routes: {
'videoLibrary' : function() { this.app.videoLibrary(); }
}
});
var Application = _.extend({}, Backbone.Events, {
initialize: function() {
this.router = new Router( this );
this.listenTo( Backbone, 'video:uploaded', function() {
this.router.navigate('/videoLibrary');
this.videoLibrary();
});
},
videoLibrary: function() {
//do useful stuff
}
});
var uploadView = Backbone.View.extend({
//...
uploadVideo: function() {
$.ajax({
//...
success: function() { Backbone.trigger('video:uploaded'); }
});
}
});
Your view does not need or want to know what to do when the user is done uploading, this is somebody else's responsibility. In this example, the router is just an entry point for the application's functionality, an event generated by the uploadView is another. The router always reflects the application state through hash changes and history but does not implement any functionality.
Testability
By separating concerns, you are enhancing the testability of your application. It's easy to have a spy on Backbone.trigger and make sure the view is working properly. It's less easy to mock a router.
Modules management
Also, if you use some module management like AMD or CommonJS, you will have to pass around the router's instance everywhere in the application in order to call it. Thus having close coupling in your application an this is not something you want.
In my opinion it's considered bad practice because you should imagine a Backbone application not like a Ruby On Rails application but rather like a Desktop application.
When I say RoR, I'm just saying a framework supporting routing in sense that a route brings you to a specific call to the controller to run a specific action (imagine a CRUD operation).
Backbone.history is intended just as a bookmark for the user so he can, for example, save a specific url, and run it again later. In this case he will find the same situation he left before.
When you say:
In my opinion it is not really bad to call the navigate function with
the trigger:true option. The route function could upon calling always
check if the considered data is already loaded and show this loaded
data instead of doing the whole work all over again...
That to me sounds smelly. If you are triggering a route and you are checking for the data to see if you have it, it means that you actually already had them so you should change your view accordingly without loading again the entire DOM with the same data.
That said trigger:true is there so do we have reason use it? In my opinion it is possible to use it if you are completely swapping a view.
Let's say I have an application with two tabs, one allows me to create a single resource, the other one let me see the list of the created resources. In the second tabs you are actually loading a Collection so data is different between the two. In this case I would use trigger:true.
That said I've been using Backbone for 2 weeks so I'm pretty new to this world but to me it sounds reasonable to discourage the use of this option.
It depends on your context.
If you have done something in your current view that might affect the view you are about to navigate to, for example creating for deleting a customer record, then setting trigger to true is the right thing to do.
Think about it. If you delete a customer record don't to want to refresh the list of customers to reflect that deletion?

Resources