11

This is basically a follow up question this question: AngularJS - How to use $routeParams in generating the templateUrl?. See my code there for the proper context of this question.

All the navigation part is working great, but now when I navigate, I want to update some properties in my $scope based on the primaryNav and secondaryNav. I thought I could do something with $watch but I can't seem to get anything to work. Here are a few things I tried:

$scope.$watch($location.path(), function() {...}); //result in js error
$scope.$watch($location, function() {...}); //function runs once on page load, but not after that
$scope.$watch($window.location, function() {...}); //function runs once on page load, but not after that
$scope.$watch(window.location, function() {...}); //function runs once on page load, but not after that
$scope.$watch(window.location.href, function() {...}); //results in js error

I could probably create some method in my controller that would take these navs and update everything and navigate off and just add a ng-click to all the anchor tags. However, one thing I really liked about AngularJS was being to use real URL-looking values for hrefs (e.g. <a href="#/priNav/secNav">Foo</a>). Is it not possible to update my model based on the changing URL when I route without going through some method on the controller? I hope it makes sense what I'm asking.

Community
  • 1
  • 1
dnc253
  • 39,967
  • 41
  • 141
  • 157

1 Answers1

33
 $scope.$watch(function() {
    return $location.path();
 }, function(){
    ...
 });

you should pass a function or a string that can be evaluated inside of the scope

Kenneth Lynne
  • 15,461
  • 12
  • 63
  • 79
Renan Tomal Fernandes
  • 10,978
  • 4
  • 48
  • 31
  • Ahh... I forgot about watching a function. Everything I was trying was on a string. `$scope.$watch($location.path, function(){});` doesn't work, but `$scope.$watch(function() { return $location.path() }, function(){...});` does. Thank you! – dnc253 Jul 19 '12 at 23:27
  • 2
    Thanks! It works even for [$location.search](http://sharepointkunskap.wordpress.com/2012/11/22/angularjs-sync-location-search-with-an-input-value/) – Anatoly Mironov Jan 28 '13 at 13:40