简体   繁体   中英

Angularjs regex routes for url

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM