微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

angularjs – Angular $location.path不工作

我有一个类似于 this one的问题,但不同。

这里我试图为一个window.postMessage处理程序添加一个事件监听器。

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
  });
});

Angular不能识别$ location.path。

一个问题说,我应该在范围上调用$ apply(),但是我可用的唯一范围是$ rootScope,并调用$ apply()似乎不工作。

对答案的评论表明,范围可以得到

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

但是这给了我$ rootScope,它不工作。

如何获得角度来重新定位$ location.path()中的更改?有没有更好的方式注册一个消息回调的方式,我可以改变路径?

你应该在$ apply()方法中运行表达式as function
app.run(function ($location,function(e) {
      $rootScope.$apply(function() {
        $location.path("/abc");
        console.log($location.path());
      });
  });
});

documentation – ng.$rootScope.Scope

如果你想提高可测试性,使用$ console而不是控制台,并注入那个对象。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐