角度 $location.path 不起作用 [英] Angular $location.path not working
问题描述
我有一个类似于这个的问题,但不同.
I have a question similar to this one, but different.
在这里,我尝试为 <添加事件侦听器code>window.postMessage 处理程序.
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
});
});
Angular 无法识别 $location.path
.
The $location.path
isn't being recognised by Angular.
另一个问题说我应该在作用域上调用 $apply()
,但我唯一可用的作用域是 $rootScope
并调用 $apply()
似乎不起作用.
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()
但这给了我 $rootScope
,它不起作用.
but this gives me the $rootScope
, which doesn't work.
我如何获得角度来重新调整 $location.path()
中的变化?是否有更好的方法来注册 message
回调,以便我可以更改路径?
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?
推荐答案
您应该像
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
并注入该对象.
If you want to improve testability, use $console
instead of console
and inject that object as well.
这篇关于角度 $location.path 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!