2

In ui-router, when you call state.go, you can define options to prevent the location from changing by passing {location:false}. However, how do I define a state using $stateProvider.state so it doesn't change the location? I've defined a rule for custom URL handling, but now it is changing the location value.

I have foo state -

  $stateProvider
    .state('foo', {
      url: '/foo'
      templateUrl: '',
      controller: function($scope) {
        console.log('made it!');
      }
    });

I have a custom rule -

   $urlRouterProvider.rule(function ($injector, $location) {
     // some logic
     return '/foo';
   });

This works exactly how I want it to except that is changes the location and appends #/foo to the location. I don't want it appended.

Josh Unger
  • 6,717
  • 6
  • 33
  • 55

1 Answers1

2

I created working example here. It is extended version of the solution presented here: How not to change url when show 404 error page with ui-router

There is a snippet of code, which should show how to use "foo" state without url change.

Firstly, there is our rule, which will redirect to 'foo' state - just in case if the /home is passed as url (an example of decision)

  $urlRouterProvider.rule(function($injector, $location) {

    if ($location.path() == !"/home") {
      return false;
    }
    var $state = $injector.get("$state");
    // move to state, but do not change url
    $state.go("foo", {
      location: false
    })
    return true;
  });

Here are our example states, which do have url setting

  // States
  $stateProvider
    .state('home', {
      url: "/home",
      templateUrl: 'tpl.html',
    })
    .state('parent', {
      url: "/parent",
      templateUrl: 'tpl.html',
    })
    .state('parent.child', {
      url: "/child",
      templateUrl: 'tpl.html',
      controller: 'ChildCtrl',
    })

Foo does not have url

    .state('foo', {
      //url: '/foo',
      templateUrl: 'tpl.html',
    });

Check it here

Community
  • 1
  • 1
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335