AngularJs 更改 $location.path 不起作用



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

我对 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>

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

对我来说效果很好的很简单:

$window.location.assign(newURL);

可能是你的问题是点击标签进行一些导航...

不是"正确"的答案,但有一些探索的方法:

  • 尝试删除 href 中的 JavaScript
  • 将"a"替换为"按钮">
  • ng-click="changeLanguage('it,$event(" 和 changeLanguage 函数:event.preventDefault(( (或某些 stopPropagation(

希望它能有所帮助..

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

最新更新