Matej
Matej

Reputation: 9805

UI-Router Let URL Pass when not defined in a state

I would like to use Angular UI-Router however I would need it to let any url pass through the browser (and make the browser navigate the page) which isn't defined (the url) in the $stateProvider or $urlRouterProvider.

I've searched through their documentation, API etc but cannot find reference for this, other than $state.reload() which i've used before..

Upvotes: 3

Views: 927

Answers (1)

Jeff French
Jeff French

Reputation: 1029

UPDATED: See update at the bottom.

From your comments I'm assuming the following:

  • Your Angular app lives at the root of the domain foo.com/
  • You are using HTML5 Mode so your app responds to "natural" urls like foo.com/thing1 and foo.com/thing2
  • You have some other app (not your main Angular app) that lives at foo.com/admin

Unfortunately, you can't have a url "pass through" like you want it to. :(

Your options are:

  • Move your Angular app into a subdirectory like foo.com/app. Then your app will respond to URLs like foo.com/app/thing1 and foo.com/app/thing2.
    • This is really the only choice if you want to use HTML5 routing mode to get "natural" looking urls.
  • Turn off HTML5 routing mode so that your Angular app lives at http://foo.com/#/ and responds to urls like foo.com/#/thing1 and foo.com/#/thing2. Then when your user visits foo.com/admin the url will fall through to the server and get whatever app is served there.

NOTE: This applies to both regular Angular routing using $routeProvider as well as using Angular-UI's $stateProvider.

UPDATE:

In order to get this to work you have to get the url change to happen outstide of Angular. Here's one method that will work but it has quite a smell to it IMO and will likely be quite fragile and difficult to maintain.

angular.module('myApp', [])
   .run(function($rootScope, $window){
      $rootScope.$on('$locationChangeStart', function(event, newUrl, oldUrl){
        // You'll probably want to just watch the path and build the full url
        // based on your environment, but this will get you started.
        if(newUrl === 'http://127.0.0.1/admin') {
          // prevent Angular from continuing with the location change
          event.preventDefault();
          // $window is an Angular wrapper around the global ``window`` object.
          // This causes the browser to go to the new url outside of Angular
          $window.location.href = newUrl;
        }
      });
});

Of course for this to work your server must be setup to serve some other app at the /admin path. Also, when your user navigates back to your Angular app it will lose all state as the Angular app will start up fresh again. Plus, your user will have to navigate back to the root of your Angular app. If the user goes from foo.com/ to foo.com/thing1 to foo.com/admin they will need to navigate back to foo.com/ to get back into your Angular app.

Upvotes: 2

Related Questions