Joe Joe - 4 months ago 101
AngularJS Question

Angular $location.path not working

I have a question similar to this one, but different.

Here I am trying to add an event listener for a

handler. ($location, $window, $rootScope) {
$window.addEventListener('message', function(e) {
console.log($location.path()); // this prints "/abc" as expected

$rootScope.$apply(); // this has no effect

$scope = angular.element(document).scope(); // this is the same as $rootScope
$scope.$apply(); // so this also has no effect

isn't being recognised by Angular.

The other question says that I should call
on the scope, but the only scope available to me is
and calling
on that doesn't seem to work.

A comment on the answer suggests that a scope can be got with

$scope = angular.element(document).scope()

but this gives me the
, which doesn't work.

How do I get angular to regocnise the change in
? Is there a better way to register a
callback in such a way as I can change the path?


You should run the expression as function in the $apply() method like ($location, $window, $rootScope) {
  $window.addEventListener('message', function(e) {
      $rootScope.$apply(function() {

See documentation - ng.$rootScope.Scope.

If you want to improve testability, use $console instead of console and inject that object as well.