Search code examples
angularjsangularjs-routing

AngularJS $location.path() changed after upgrading to 1.1.15


I have a NavigationController that has a selectedItem for the current selected item in a navigation list. It uses $location.path() to try and set it to a default value. It's in hashbang mode. Here is a simplified version:

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

And the 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>

And the config:

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

The problem is that when I navigate to /home/index (without a hash bang) $location.path() returns "/index" where it used to return null prior to 1.1.15. However, if I go to "/home/index#/dashboard it returns "/dashboard" as expected. I tried redirecting when someone goes to "/" to "/dashboard", but NavigationController is called prior to being redirected so it continues to get "/index".

So how can I at least tell when the hashbang is not included? $location.hash() always seems to return "". I don't want to hard code "/index" in my code to know when nothing is on the URL.


Solution

  • I think you want to use the $route service and hook into the $routeChangeSuccess event.

    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;
        }
    });