Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
675 views
in Technique[技术] by (71.8m points)

angularjs - How would I have ui-router go to an external link, such as google.com?

For example:

 $stateProvider
            .state('external', {
                url: 'http://www.google.com',

            })

url assumes that this is an internal state. I want it to be like href or something to that effect.

I have a navigation structure that will build from the ui-routes and I have a need for a link to go to an external link. Not necessarily just google, that's only an example.

Not looking for it in a link or as $state.href('http://www.google.com'). Need it declaratively in the routes config.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Angular-ui-router doesn't support external URL, you need redirect the user using either $location.url() or $window.open()

I would suggest you to use $window.open('http://www.google.com', '_self') which will open URL on the same page.

Update

You can also customize ui-router by adding parameter external, it can be true/false.

  $stateProvider
  .state('external', {
       url: 'http://www.google.com',
       external: true
  })

Then configure $stateChangeStart in your state & handle redirection part there.

Run Block

myapp.run(function($rootScope, $window) {
  $rootScope.$on('$stateChangeStart',
    function(event, toState, toParams, fromState, fromParams) {
      if (toState.external) {
        event.preventDefault();
        $window.open(toState.url, '_self');
      }
    });
})

Sample Plunkr

Note: Open Plunkr in a new window in order to make it working, because google doesn't get open in iFrame due to some security reason.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...