AngularJS $ location.path()在升级到1.1.15后发生了变化

时间:2013-06-21 00:49:58

标签: angularjs angularjs-routing

我有一个NavigationController,它有一个selectedItem用于导航列表中当前选定的项目。它使用$ location.path()来尝试将其设置为默认值。它处于hashbang模式。这是一个简化版本:

App.controller("NavigationController", ['$scope', '$location', function($scope, $location) {
   $scope.currentSelection = $location.path() || "/dashboard";
   $scope.select = function( name ) {
       $scope.currentSelection = name;
   }
}]);

和html:

<body ng-app="App">
  <div class="container-fluid absoluteFill">
    <div class="row-fluid fill" ng-controller="NavigationController">
       <div class="span2 nav-bubble fill">
          <ul class="nav nav-list">
             <li>Option 1</li>
             <li>Option 2</li>
             <li>Option 3</li>
          </ul>
       </div>
       <div ng-view></div>
     </div>
  </div>
</body>

配置:

angular.module("App", ["ngResource"])
   .config(function($routeProvider) {
      $routeProvider.
         when( '/', { redirectTo: '/dashboard' }).
         when( '/dashboard', {
            controller: 'DashboardController',
            templateUrl: '/gpa/app/views/dashboard.html'
        }).
        otherwise({redirectTo: '/'});
   })

问题在于,当我导航到/ home / index(没有哈希爆炸)时,$ location.path()返回“/ index”,用于在1.1.15之前返回null。但是,如果我转到“/ home / index#/ dashboard,它会按预期返回”/ dashboard“。当有人转到”/“到”/ dashboard“时,我尝试重定向,但在重定向之前调用NavigationController,所以它继续获得“/ index”。

那么我怎么能至少告诉什么时候不包括hashbang? $ location.hash()似乎总是返回“”。我不想在我的代码中硬编码“/ index”以了解网址上什么也没有。

1 个答案:

答案 0 :(得分:0)

我认为你想使用$route服务并挂钩$routeChangeSuccess事件。

App.controller("NavigationController", function($scope, $location) {
    $scope.$on("$routeChangeSuccess", function (scope, next, current) {
        $scope.currentSelection = $location.path() || "/dashboard";
    });
    $scope.select = function( name ) {
        $scope.currentSelection = name;
    }
});