Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - Update model based on URL

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.

like image 759
dnc253 Avatar asked Jul 19 '12 06:07

dnc253


1 Answers

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

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

like image 149
Renan Tomal Fernandes Avatar answered Oct 01 '22 12:10

Renan Tomal Fernandes