AngularJS $location.url不起作用,location.href起作用
AngularJS $location.url不起作用,location.href起作用
当我尝试在我的控制器中更改位置时,它加载服务器的根目录,而不是特定的页面:\n
'use strict'; eventsApp.controller('TestController', function TestController($scope, $location){ console.log('test comes here!'); $scope.makeTest = function(){ $location.url('/test'); } });
\n我有一个像这样的路由器:\n
'use strict'; var eventsApp = angular.module('eventsApp', ['ngResource','ngSanitize']) .config(function($routeProvider, $locationProvider){ $routeProvider .when('/test',{ templateUrl:'templates/test.html', controller:'TestController' }).otherwise({ templateUrl:'templates/default.html', controller:'DefaultController', redirectTo:'' }); $locationProvider.html5Mode(true); });
\n在我的index.html中,我设置了指令:\n
\n似乎每次都会执行otherwise。然而,如果我使用\n
location.href = '/test';
\n而不是\n
$location.url('/test');
\n,那么它会起作用。\n我对这样的行为一无所知。你有任何想法吗?
AngularJS的$location.url不起作用,但location.href可以起作用的原因是,$location.url方法在执行时,可能会与当前正在执行的$scope.apply()冲突,导致无法正常执行。解决方法是使用$timeout作为一个变通方法,将$location.url(newUrl)方法放在$timeout函数内部执行,可以解决该问题。
代码示例:
$scope.myFunction = function() { $timeout(function() { $location.url(newUrl); }); }
另外一个解决方法是,在你的api加载完成后,设置一个全局变量,将其设置为"loaded",然后更新你的函数/调用涉及$scope的操作。
代码示例:
$scope.myFunction = function() { if (globalVariable === "loaded") { $location.url(newUrl); } }
通过这样的操作,可以解决在ng-click处理程序中$location.url方法不起作用的问题。
AngularJS中的$location.url()方法在跳转到另一个URL时可能会出现问题,即它会调用代码但并不会实际跳转。如果遇到这种情况,可以使用$window服务来实现跳转,代码如下:
$window.location.assign(url);
问题的原因可能是$location.url()方法在处理跳转时存在一些bug或者其他不明原因导致的错误。而使用$window.location.assign(url)方法则能够成功实现跳转。
解决方法就是使用$window.location.assign(url)方法来代替$location.url()方法进行跳转。这样可以避免出现问题,并且确保跳转操作的正常执行。
通过以上方法,可以解决AngularJS中$location.url()方法无法正常跳转的问题。