Angular JS $location.path() getter 未更新

Angular JS $location.path() getter not updating

我想使用 $location.path() 方法来 return URL 路径,这样我就可以在 ng-hide 指令中编写一些条件语句。我在控制器中创建了以下内容:

$scope.pathLocation = $location.path();

然后我在我的 html 中插入 {{pathLocation}} 只是为了确保它 return 是正确的路径,确实如此。当我加载不同的视图时,问题就来了。 pathLocation 不会更新。如果我在新的页面视图上手动刷新浏览器,它会。 `

这是我的代码的简化版本: 控制器:

(function(){
  var amApp = angular.module('amApp', ['ngRoute', 'ngCookies','ngAnimate' ]);

  amApp.controller('WelcomeController', ['$scope', '$location', function WelcomeController($scope, $location) {
    $scope.pathLocation = $location.path();
  }]);
})();

这里是 HTML:

<html lang="en" ng-app="amApp">
  <body ng-controller="WelcomeController as welcome">
    <nav>menu's here to different views in SPA</nav>
    {{pathLocation}}
    <div ng-view></div>
  </body>

正如我在评论中提到的,您的代码中没有任何内容会更新您的 pathLocation 属性。尝试添加这个

$scope.$on('$locationChangeSuccess', function() {
    $scope.pathLocation = $location.path();
});

在范围内发布函数:

amApp.controller('WelcomeController', ['$scope', '$location', function WelcomeController($scope, $location) {
    //$scope.pathLocation = $location.path();
    $scope.locationPathFn = $location.path;
}]);

然后执行HTML中的函数:

<html lang="en" ng-app="amApp">
  <body ng-controller="WelcomeController as welcome">
    <nav>menu's here to different views in SPA</nav>
    {{locationPathFn()}}
    <div ng-view></div>
  </body>

然后在每个摘要周期中检查 $location.path() 函数并使视图保持最新。