javascript - Angularjs 正则表达式 url 路由

标签 javascript angularjs

我尝试创建一个路由 /: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 网址。

Demo

关于javascript - Angularjs 正则表达式 url 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27799258/

相关文章:

javascript - 从 JSON 形成构造函数

javascript - 在 foreach 循环内使用 <select> 元素的 Knockout JS 中的错误

javascript - 在 Angular js中使用指令的数据表

javascript - 在混合应用程序中找不到 AngularJS

javascript - 在 AngularJS 中使用 $location 对象的说明

javascript - 同步,即使有 promise ,是否需要一些事件监听器?

javascript - 如何在不出错的情况下评论 EJS 代码(JS Node )

javascript - 返回数组中至少出现 3 次的值

javascript - 如何使用 Controller 变量和 ng-click 来切换类?

javascript - Angular 2/Nodejs 部署到 heroku 错误 heroku-postbuild : `ng build`