gpt4 book ai didi

angularjs - $location.path() 在第二次点击后更新?

转载 作者:行者123 更新时间:2023-12-02 22:42:25 24 4
gpt4 key购买 nike

[第二个问题(见下文) - 在一个 Controller 中设置的 rootScope 变量在第二个同级 Controller 中不可见?]

可能的重复: angularjs $location.path only updates URL on second click - 问题的原因和答案似乎与我的更基本的情况无关

根据 angularjs 文档(https://docs.angularjs.org/guide/ $location):

[The $location service]
Maintains synchronization between itself and the browser's URL when the user
...
Clicks on a link in the page.

我知道 $location.path() 反射(reflect)了浏览器中的当前 url,但是当我单击链接来更改 View 时,会表现出奇怪的行为: $location.path() 不会“更改”第一次点击链接,此后每次都会更改为上次点击的链接

要查看此内容,请转到此处:http://jsfiddle.net/7Ah2W/

我尝试了一种解决方法,必须使用 setter 重载手动设置 $location.path()。

在这样做的过程中,我发现了我对 angularjs 理解的另一个缺陷。我尝试在 rootScope 中设置一个变量来反射(reflect)“当前路径”。这个想法是 View 会自动检测变量的变化并更新。不是每个作用域都继承自 rootScope 吗?

这是一个jsfiddle

为什么我期望 $rootScope.currentPath 在“NavCtrl”中更改并在“CtrlTwo”中更新没有得到满足?

我的最终目标是让我的导航栏在单击 View 中的链接时自动更改。类似于 https://console.developers.google.com如果您单击您的项目,左侧​​的导航将更改为 API&Auth、设置等。

最佳答案

它似乎总是“落后”的原因是您在实际的 Angular 页面进程运行之前访问 $location.path() 。奇怪的是,如果您只添加一个 $timeout 甚至 0 毫秒延迟,它就会按预期工作。

    $timeout(function () {
$scope.currentPath = $location.path();
}, 0);

<强> jsFiddle example

$rootScope 是全局范围,而不是常规的 $scope,后者基本上是 Controller 和 View 之间的粘合剂。

例如,我在第一个 Controller 中设置了$rootScope.test = 123;,在第二个 Controller 中我警告该变量并获取结果。 <强> jsFiddle $rootScope example 。小心 $rootScope,它创建全局范围的变量

关于angularjs - $location.path() 在第二次点击后更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24143945/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com