Angular $location.path not working

后端 未结 4 824
生来不讨喜
生来不讨喜 2020-11-28 08:45

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 ($         


        
相关标签:
4条回答
  • 2020-11-28 09:08

    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.

    0 讨论(0)
  • 2020-11-28 09:08

    There is solution without $timeout.

    Just prevent redirect to default state before using $state.go

    event.preventDefault();
    $state.go('root');
    
    0 讨论(0)
  • 2020-11-28 09:10

    I had the same problem, my mistake was that I was running the ng-click directive badly on my item.

    Bad example:

    <a **href="#"** ng-click="myFunctionChangeLocationPath()">...
    

    Example well:

    <a ng-click="myFunctionChangeLocationPath()">...
    

    And so you can correct the problem!

    0 讨论(0)
  • 2020-11-28 09:11

    The accepted solution is not the appropriate way to do it. Ideally you shouldn't need to interfere with the digest cycle (which $apply() does).

    The best way according to me is calling $location.path() from the MainController. Use $emit - $on to send it to the MainController and have a function call $location.path from there. It will redirect you flawlessly without having to interfere with the digest cycle. I hope this helps someone.

    0 讨论(0)
提交回复
热议问题