Angular JS $ location.path()getter没有更新

时间:2016-10-19 22:39:10

标签: angularjs routes ngroute

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

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

然后我在我的html中插入{{pathLocation}}只是为了确保它返回正确的路径,它就是这样。当我加载不同的视图时出现问题。 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>

2 个答案:

答案 0 :(得分:1)

正如我的评论中所述,您的代码中没有任何内容更新您的pathLocation媒体资源。尝试添加此

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

答案 1 :(得分:0)

在范围上发布功能:

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()函数并使视图保持最新。