Sunday, October 4, 2015

Prevent ui.router's ui-sref from reloading the page

If a ui-router link points the page where it resides, it will cause a page reload on the page(s) that are reloaded, and thus it will cause flickering or noticeable delay.

<a ui-sref="{id: ad.itemId})">{{ad.title}}</a>

To improve that, just perform ajax on an ng-click and just fetch the data that are needed to populate the information on the page, and prevent the href from reloading the page by using $event.preventDefault(). The href will just be used for bookmark purposes or if the user want to open the link on another tab or window. We can use ui.router href method for translating the state to link.

ng-click="ctrl.AppWide.edit(a.itemId); $event.preventDefault()" 
title="Change Information" 
href="{{c.$state.href('',{id: a.itemId})}}" 

To change the url after performing an ajax operation, use $state.go and pass the parameter notify false to it, so it will just change the url and not do a partial page reload.

this.$state.go('', {id: this.savedId}, {notify: false});

Note: As of the time of the time of this writing, the notify false has a bug, it invokes the originating controller twice and sometimes it rejects the link the user clicked on from going to the link's page. There's already a solution to that, but it's not yet on the latest release of angular ui.router, have to patch the ui.router manually.

Happy Coding!

No comments:

Post a Comment