小编典典

角$ location.path不起作用

angularjs

我有一个与此问题类似但又不同的问题。

在这里,我试图为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
  });
});

$location.path没有被角的认可。

另一个问题是我应该调用$apply()作用域,但是对我来说唯一可用的作用域是$rootScope调用$apply()它似乎不起作用。

对答案的评论表明,可以使用

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

但这给了我$rootScope,这是行不通的。

如何获得角度来重新确定更改$location.path()?是否有更好的方式注册message回调,以便可以更改路径?


阅读 342

收藏
2020-07-04

共1个答案

小编典典

您应该在$apply()类似方法中将表达式作为函数运行

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

请参阅文档-ng。$rootScope.Scope

如果要提高可测试性,请使用$console代替console并注入该对象。

2020-07-04