我尝试创建一个路由 /:url
来匹配 http://localhost/#/http://www.google.com
我想通过
获取 Controller 中的 url 参数var url = $stateParams.url; // url = http://www.google.com
有什么办法可以实现这个场景吗?请推荐,谢谢。
最佳答案
在 url 中传递编码的斜杠非常困难,因为浏览器会将其更改为斜杠。我想出的唯一解决方案是对斜杠进行双重编码。我用过this encoder进行编码,但如果需要,可以使用 encodeURIComponent
在您的 Angular 应用程序中完成。这意味着网址改为 #/http%3A%252F%252Fwww.google.com
。
要设置参数,您首先必须将其添加到 app.js
中的路由配置中。我添加了名为 url
的参数,并使用 ?
符号将其设为可选:
app.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when('/:url?', {
templateUrl: 'view.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
});
然后在你的 Controller 中你可以使用$routeParams
来获取url。但由于斜杠是双重编码的,因此您需要使用 decodeURIComponent
来解码 url:
app.controller('MainCtrl', function($scope, $routeParams) {
$scope.url = decodeURIComponent($routeParams.url);
})
单击演示中的 a
链接获取 Google 网址。
关于javascript - Angularjs 正则表达式 url 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27799258/