Reputation: 525
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.
Upvotes: 0
Views: 872
Reputation: 7958
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.
Upvotes: 1