0

I try to create a route /:url to match http://localhost/#/http://www.google.com

and I want to get url param in controller by

var url = $stateParams.url; // url = http://www.google.com

Is there any way to achieve that scene? Please suggest, thanks.

1 Answer 1

1

It's quite difficult to pass encoded slashes in urls as the browser will change it to a slash. The only solution I came up with is to double encode the slashes. I used this encoder to do the encoding but it could be done in your angular app if needed using encodeURIComponent. That means the url is instead #/http%3A%252F%252Fwww.google.com.

To setup the parameter you first have to add it to the routing config in app.js. I've added the parameter called url and made it optional with the ? symbol:

app.config(function ($routeProvider, $locationProvider) {
    $routeProvider
      .when('/:url?', {
        templateUrl: 'view.html',
        controller: 'MainCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });
});

Then in your controller you can use $routeParams to get the url. But since the slashes are double encoded you need to use decodeURIComponent to decode the url:

app.controller('MainCtrl', function($scope, $routeParams) {
  $scope.url = decodeURIComponent($routeParams.url);
})

Click the a link in the demo for the google url.

Demo

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.