尽管设置$ apply()或$ timeout,$ location.path()仍无法正常工作

时间:2014-11-24 18:48:11

标签: angularjs

我将自己的Auth服务放在我正在构建的AngularJS应用程序中,在我的控制器中,我有以下代码来调用一个服务器。该服务处理登录,如果有匹配我想重定向到我的主页/主页...这是我的控制器代码

$scope.login = function (user) {
      // we have the user name and password let's see if account exists...
      AuthService.login(user).success(function (response) {

        // what have we received? if the length > 0 we have a match
        if (response.length !== 0) {
          StorageService.makeLocalKey('uuid', response[0].uuid); // this works!
          $location.path('/'); // the current path is /login, nothing happens, the browser path/ window doesn't change? 
          console.log($location.path()); // this gives '/' but I am not taken to main route and the URL isn't changed in the browser, it's still /login
        } else {
          $scope.errorNotFound = true;
        }

}

现在我用

替换$location.path('/');
$scope.$apply(function () {
  $location.path('/');
});

我在控制台中收到以下错误:Error: [$rootScope:inprog] $digest already in progress

所以我尝试了以下......

$timeout(function () {
  $location.path('/');
});

但没有任何反应!我做错了什么?

3 个答案:

答案 0 :(得分:1)

您是否尝试过了一段延迟?

$timeout(function() {
  $location.path('/');
}, 100);

或者您也可以尝试两者的组合:

$timeout(function() {
  $location.path('/');
  $scope.$apply();
}, 100);

答案 1 :(得分:0)

出于两个原因,您不需要$apply范围:

  • $ location仅在需要时执行$apply
  • 您在控制器内,$apply正在为任何人$digest编辑 $scope中的变化 我不知道您的所有代码,但在更改位置后立即调用replace()让Angular知道溃败已更改。这可能会解决。

答案 2 :(得分:0)

我是从元素的ng-click事件中得到此问题的。原因是href ="#"在我的$ location.path('')代码执行之前,标记的一部分导致重定向....一旦我删除了href ="#"属性它工作正常。

希望这有助于其他人。

相关问题