ADP ADP - 2 months ago 34
AngularJS Question

Angular JS $location.path() getter not updating

I want to use the $location.path() method to return the URL path so I can write some conditional statements in an ng-hide directive. I created the following in my controller:

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

I then inserted {{pathLocation}} in my html just to make sure it was returning the correct path, which it is. The problem comes when I load a different view. The pathLocation doesn't update. If I manually refresh my browser on the new page view, it does. `

Here is an abbreviated version of my code:

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

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

Here is the HTML:

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


As mentioned in my comment, nothing in your code updates your pathLocation property. Try adding this

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