【问题标题】:AngularJs changing $location.path does not workAngularJs 更改 $location.path 不起作用
【发布时间】:2014-12-14 16:23:29
【问题描述】:

我意识到这个问题之前已经出现过。 但似乎没有一个答案可以解决这个问题。

我对 Angular 有一定的了解,并且编写了相当多的 Angular 代码,我不是一个完整的初学者。

我已经开始开发 MEAN 应用程序,所以所有客户端都是 Angular。经过两天的努力,我无法让一个完全简单的 location.path(newPath) 在控制器的 $scope 中的函数中工作。

'use strict';

angular.module('core').controller('HeaderController', 
        [   '$scope', 
            '$location',
function($scope, $location) {


    //THIS LINE OF CODE, ON ARRIVAL IN THE CONTROLLER, WORKS
    //- it changes the path no problem.
    //$location.path('/it/vino/chianti/ChiantiClassico');   


    //But trying to set $location.path() DOES NOT WORK IN THE
    //FOLLOWING FUNCTION.
    //This function is called correctly from an ng-click event on a link. 
    //Therefore there should be no need to call apply(). 
    //However I have also tried both $apply and $timeout.

    $scope.changeLanguage = function(lang){

        //Right, let's try setting the path..
        $location.path('/it/vino/chianti/ChiantiClassico');

        //now we log $location.path() in the console and it 
        //gives the correct answer, which is:
        //'/it/vino/chianti/ChiantiClassico',
        //(but the path does not actually change in the browser address bar).
        console.log('$location.path():', $location.path()); //correct!

        //But if I also log the location object and I look inside, 
        //the path hasn't changed there !
        console.log('$location:', $location); //The path is the old one!

        //And the address bar has not changed
    };


}//end function

]);

我已经调试并搜索了寻找另一个 $location 对象或其他错误的对象。 - 但是只有一个 $location 对象 - 在堆栈的“闭包”部分中找到。

我在这里看不到任何类型的回调错误,我没有尝试使用尚未定义的对象或类似的东西。

为了完整起见,这里是视图中的调用链接代码,这里没什么奇怪的,我也尝试过从按钮调用,函数调用正确:

<a href="javascript:;" data-ng-click="changeLanguage('it')">italiano</a>

【问题讨论】:

  • 您是否尝试删除 href="javascript:;" ?
  • 我改成按钮了,结果一样
  • 你在用 $timeout 做一些异步的事情吗?
  • 不,我把它放在那里只是为了尝试 $timeout。那里没有现在使用它的代码。我会编辑并删除它。
  • 你有没有得到任何地方?我有一个类似的问题。除了任何重定向都将我带回我的根路径! ://

标签: angularjs


【解决方案1】:

我在同样的问题上挣扎了一段时间。问题在于使用新创建对象的 ID 更新 URL(ID 由 DB 生成并作为保存过程的一部分检索)。

对我有用的只是:

$window.location.assign(newURL);

【讨论】:

  • 好吧,我不能完全给你答案,但是 +1 因为对于处于类似困境的人来说,这是一个有趣的解决方案
【解决方案2】:

可能是您的问题是单击标记进行一些导航...

不是一个“真实”的答案,而是一些探索的方法:

  • 尝试删除href中的javascript
  • 将“a”替换为“按钮”
  • ng-click="changeLanguage('it,$event)" 并在 changeLanguage 函数中: event.preventDefault()(或一些 stopPropagation)

希望对你有帮助..

【讨论】:

  • 谢谢蒂埃里,但我确信这不是问题所在。那个代码没问题。你可以把调用代码改成:,没有区别。
【解决方案3】:

我遇到了同样的问题,最后,我使用了这段代码: $window.location = '/#/path/to/xx' :

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-11
    • 2015-09-19
    • 2013-10-30
    相关资源
    最近更新 更多