Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
822 views
in Technique[技术] by (71.8m points)

angularjs - 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 window.postMessage handler.

app.run(function ($location, $window, $rootScope) {
  $window.addEventListener('message', function(e) {
      $location.path("/abc");
      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
  });
});

The $location.path isn't being recognised by Angular.

The other question says that I should call $apply() on the scope, but the only scope available to me is $rootScope and calling $apply() 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 $rootScope, which doesn't work.

How do I get angular to regocnise the change in $location.path()? Is there a better way to register a message callback in such a way as I can change the path?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should run the expression as function in the $apply() method like

app.run(function ($location, $window, $rootScope) {
  $window.addEventListener('message', function(e) {
      $rootScope.$apply(function() {
        $location.path("/abc");
        console.log($location.path());
      });
  });
});

See documentation - ng.$rootScope.Scope.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...