0

i have .js file as below

routerApp.config(function ($stateProvider, $urlRouterProvider) { 
    $urlRouterProvider.otherwise(function ($injector, $location) {
    var $state = $injector.get('$state');
    var path = $location.protocol();
    if (path == 'http') {
       $state.go('external');
    }
    else {
        return '/home';
    }
});

$stateProvider

    // HOME STATES AND NESTED VIEWS ========================================
    .state('home', {
        url: '/home',
        templateUrl: 'routing.html'
    })
    .state('external', {
        onEnter: function ($window) {
         $window.open('http://www.google.com', '_self');
        }
    });

});

above code works fine when path != 'http', it will redirect to routing.html. But when path == 'http', it should call external state and redirect to external url. Here path == 'http' condition is not working. How to call external url here? and in state I am calling external onEnter. Can I do it without OnEnter?

  • I'm a little confused on the purpose of what you are trying to do. `otherwise` is meant for non-matching routing hits. The first hit to your site will most likely match the otherwise function. What is the interest of sending them to another site? – unflores Mar 03 '16 at 14:38
  • I am trying to do conditional otherwise. my target is incase my if condition is true then it should redirect me to external url(in this case google.com) and if it is false then redirect to internal .html file. I am able to achieve false condition. My question is incase true then how to redirect to external url? –  Mar 03 '16 at 14:52
  • @aparnakm I think this will help you http://stackoverflow.com/a/30221248/2435473 – Pankaj Parkar Mar 03 '16 at 15:53
  • Just a question, what's the goal of it ? Forbid http connection ? a redirect from server-side would be far more easier, http/https is not the concern of the front-end – Walfrat Mar 03 '16 at 16:13

2 Answers2

1

This worked for me:

$urlRouterProvider.otherwise(function ($injector, $location) {
   var protocol = $location.protocol();
   if (protocol == 'http') {
      window.open('http://www.google.com', '_self');
   }
   else {
       return '/home';
   }
});
unflores
  • 1,764
  • 2
  • 15
  • 35
  • though i don't see the point of the var $state = $injector.get('$state'); when $state is not used :) – Walfrat Mar 03 '16 at 15:23
  • @unflores I want to call state 'external' on true. I don't want to give url directly. is it possible? –  Mar 03 '16 at 15:36
  • @walfrat, yeah, I just modified his original function. I'll edit it. – unflores Mar 03 '16 at 16:08
0

This is a bit different but probably something like this will work :)

$rootScope.on("$stateChangeStart", function(event, toState){
    if(toState.name == 'external'){
         event.preventDefault();
         window.open('http://www.google.com', '_self');
    }
});
Walfrat
  • 5,363
  • 1
  • 16
  • 35