Monday 25 December 2017

AngularJS UI Router - change url without reloading state

itemprop="text">

Currently our project is using default
$routeProvider, and I am using this "hack", to change
url without reloading
page:




services.service('$locationEx',
['$location', '$route', '$rootScope', function($location, $route, $rootScope)
{
$location.skipReload = function () {
var lastRoute =
$route.current;
var un = $rootScope.$on('$locationChangeSuccess', function ()
{
$route.current = lastRoute;
un();
});

return $location;
};
return
$location;

}]);


and
in
controller



$locationEx.skipReload().path("/category/"
+
$scope.model.id).replace();


I
am thinking of replacing routeProvider with
ui-router for nesting routes, but cant find this in
ui-router.




Is
it possible - do the same with
angular-ui-router?



Why
do I need this?
Let me explain with an example :
Route for creating
new category is /category/new
after
clicking on SAVE I show success-alert
and I want to change route /category/new to
/caterogy/23 (23 - is id of new item stored in
db)



Answer




Simply you can use
$state.transitionTo
instead of $state.go .
$state.go calls $state.transitionTo
internally but automatically sets options to { location:
true, inherit: true, relative: $state.$current, notify: true }
. You can
call $state.transitionTo and set notify: false
. For example:



$state.go('.detail', {id: newId})




can be
replaced
by



$state.transitionTo('.detail',
{id: newId}, {
location: true,
inherit: true,
relative:
$state.$current,
notify:
false
})



Edit:
As suggested by fracz it can simply be:



$state.go('.detail', {id: newId},
{notify: false})


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...