如何在angularjs中重定向

iJa*_*ade 2 javascript redirect angularjs angularjs-directive

这可能是一件微不足道的事情,但我是一个有角度的新手.这是我的angularjs控制器代码

    function MyCtrl1($scope, $location, $rootScope) {
  $scope.$on('$locationChangeStart', function (event, next, current) {
    event.preventDefault();
    var answer = confirm("Are you sure you want to leave this page?");
    if (answer) {

    }
  });
}
MyCtrl1.$inject = ['$scope', '$location', '$rootScope'];
Run Code Online (Sandbox Code Playgroud)

next变量中我有重定向的URL确认OK.但是如何在angularjs中完成这个事情.

Jos*_*ber 7

您不必手动执行此操作.只有在他们确认时才取消活动:

$scope.$on('$locationChangeStart', function (event, next, current) {
    if ( ! confirm("Are you sure you want to leave this page?") ) {
        event.preventDefault();
    }
});
Run Code Online (Sandbox Code Playgroud)


Ars*_*wal 6

您可以使用其他答案中提到的普通javascript,也可以使用像这样的角度提供的$ location服务

    $location.path(next)
Run Code Online (Sandbox Code Playgroud)

要么

   $location.replace(next)
Run Code Online (Sandbox Code Playgroud)

第一个添加到您当前的路径(主要是部分)

第二个替换当前路径(如google.com到yahoo.com)