2

[And a second question (see below) - rootScope variable set in one controller not visible in a second, sibling controller?]

Possible Duplicate: angularjs $location.path only updates URL on second click - the cause of the problem and the answer does not seem relevant in my, more basic, situation

As per the angularjs docs (https://docs.angularjs.org/guide/$location):

[The $location service]
Maintains synchronization between itself and the browser's URL when the user
...
Clicks on a link in the page.

I understood that $location.path() reflects the current url in the browser, but when I click a link to change the view, exhibits strange behaviour: $location.path() does not 'change' the first time one clicks on a link, and every time thereafter it will change to the link that was clicked the previous time

To see this go here: http://jsfiddle.net/7Ah2W/

I attempted a workaround whereby I must manually set $location.path() using the setter overload.

In doing so, I found another flaw in my understanding of angularjs. I tried setting a variable in the rootScope to reflect the 'current path.' The idea is that views would automatically detect the change in the variable and update. Does not every scope inherit from rootScope?

Here is a jsfiddle

Why is my expectation that $rootScope.currentPath, being changed in 'NavCtrl' and updated in 'CtrlTwo' not being met?

My end goal is to have my navigation bar automatically change when a link in the view is clicked. Similar to https://console.developers.google.com where if you click your project, the navigation to the left changes to API&Auth, settings, etc.

Community
  • 1
  • 1
user2316667
  • 5,444
  • 13
  • 49
  • 71

1 Answers1

11

The reason it seems to always be "one behind" is that you're accessing the $location.path() before the actual angular page process can run. Strangely enough if you just add a $timeout with even 0ms delay, it'll work as intended.

    $timeout(function () {
        $scope.currentPath = $location.path();
    }, 0);

jsFiddle example

$rootScope is the global scope, as opposed to the regular $scope which is basically the glue between the controller & view.

For example I set $rootScope.test = 123; in your first controller, and in the second controller I alert that variable, and get the result. jsFiddle $rootScope example. Be careful with $rootScope, it creates globally scoped variables

Mark Pieszak - Trilon.io
  • 61,391
  • 14
  • 82
  • 96
  • Thanks! Can you also explain why $rootScope isn't visible in the second controller? [EDIT] Woops! It was a typo. Thanks a lot! – user2316667 Jun 10 '14 at 14:56
  • Thanks @mcpDESIGNS, But can we know when this angularjs processing is done, so that I can run such functions inside it? See my [question](http://stackoverflow.com/q/25750587/2642351) in this relation. – Temp O'rary Sep 09 '14 at 17:30