为什么在这种情况下我需要$ timeout来更改位置?

时间:2014-03-03 17:03:16

标签: angularjs

我有以下代码:

angular.module('DemoApp')
  .controller('NavbarCtrl', ['$scope', '$rootScope', '$location', '$timeout', function($scope, $rootScope, $location, $timeout) {
    $scope.logout = function() {
      $rootScope.user = null;
      $location.path("/login");
    };
  }]);

问题是,当调用注销时,位置不会改变。但是以下代码有效(注意使用$ timeout):

angular.module('DemoApp')
  .controller('NavbarCtrl', ['$scope', '$rootScope', '$location', '$timeout', function($scope, $rootScope, $location, $timeout) {
    $scope.logout = function() {
      $rootScope.user = null;
      $timeout(function() {
        $location.path("/login");
      });
    };
  }]);

有人可以告诉我这是为什么吗?

编辑: HTML看起来像这样,位于NavbarCtrl控制器元素中:

<a href="#" ng-click="logout()"><i class="fa fa-sign-out"></i><br/>Abmelden</a>

1 个答案:

答案 0 :(得分:3)

错误的是HTML:href="#"导致位置更改,$location.path()无法再次更改。将HTML更改为href="",无需使用$timeout

相关问题