我有一个与此问题类似但又不同的问题。
在这里,我试图为window.postMessage处理程序添加事件侦听器。
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没有被角的认可。
$location.path
另一个问题是我应该调用$apply()作用域,但是对我来说唯一可用的作用域是$rootScope调用$apply()它似乎不起作用。
$apply()
$rootScope
对答案的评论表明,可以使用
$scope = angular.element(document).scope()
但这给了我$rootScope,这是行不通的。
如何获得角度来重新确定更改$location.path()?是否有更好的方式注册message回调,以便可以更改路径?
$location.path()
message
您应该在$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并注入该对象。
$console
console