角$ location.path不工作 [英] Angular $location.path not working
问题描述
我有类似这一个,但不同的问题。
I have a question similar to this one, but different.
在这里,我想添加事件侦听器的 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
});
});
的 $ location.path
是不被认可的角
另一个问题说,我应该叫 $适用()
的范围,而是提供给我的唯一范围 $ rootScope
并调用 $适用()
上似乎并没有工作。
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
,这是行不通的。
我要如何向角在regocnise $ location.path的变化()
?有没有更好的办法以这样的方式来注册的消息
回调,我可以改变路径?
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?
推荐答案
您应运行前pression如 $适用()
像<方法函数/ p>
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());
});
});
});
如果你想提高可测试性,使用 $控制台
而不是控制台
并注入该对象也是如此。
If you want to improve testability, use $console
instead of console
and inject that object as well.
这篇关于角$ location.path不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!