AngularJs $ location.path,带有完整的URL

mic*_*ght 26 angularjs

如果用户在模态中单击"确定",我想将用户路由到网址.在我的控制器中,我收到的网址就像

var newUrl = http://localhost:3000/#/dashboard

var newUrl = http://localhost:3000/#/users
Run Code Online (Sandbox Code Playgroud)

作为变量.

如果我然后使用

$location.path(newUrl);
Run Code Online (Sandbox Code Playgroud)

这是行不通的.我也试过了

$location.url(newUrl);
Run Code Online (Sandbox Code Playgroud)

但是我的URL被编码为这样.

http://localhost:3000/#/#%2Fdashboard
Run Code Online (Sandbox Code Playgroud)

有没有办法只获得网址的路径?

编辑

此代码是服务的一部分.用户在表单中进行一些输入并单击另一个链接,例如在菜单中.然后会出现一个弹出窗口,要求他跳过表单更改.如果他点击是,我会收到请求的网址.这是从我在服务器上的开发环境当然会是另一个url.所以我不能只使用

$location.path("/users")
Run Code Online (Sandbox Code Playgroud)

例如

Rob*_*cki 21

我在遇到Angular preventDefault $ locationChangeStart事件时遇到了同样的问题,强行保存,并且只在成功时重定向.我在控制器的主体中定义了以下函数:

var baseLen = $location.absUrl().length - $location.url().length;
function getPath(fullUrl) { 
    return fullUrl.substring(baseLen);
}
Run Code Online (Sandbox Code Playgroud)

它似乎不是一个干净的解决方案,但作为一种解决方案,它可以完成这项工作.如果您不知道您的网址指向同一网站,则RegEx可能会更适合您.


小智 10

你可以用$location.absUrl().

请参阅官方文档:在此处输入链接说明

这种方法只是getter.

返回完整的url表示,其中所有段都根据RFC 3986中指定的规则进行编码.

  • 正如你所说,absUrl是一个吸气剂,而不是一个二传手,所以这是如何回答这个问题的?! (13认同)

arj*_*bar 5

我可以提供不同的解决方案:

    $scope.$on('$locationChangeStart', function(e) {
      if (meetsTheRequirementsToLeave()) {
        return;
      }
      var newPath = $location.path();
      e.preventDefault();
      checkIfUserWantsToLeave().then(function() {
        $location.path(newPath);
      });
    });
Run Code Online (Sandbox Code Playgroud)

在此事件中$location.path()返回新路径.