【发布时间】: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