在Angular中,如何使用$ location.path重定向为$ http.post成功回调

Geo*_*man 72 javascript model-view-controller angularjs

我试图通过发送一个帖子到一个PHP文件来做一个简单的身份验证服务,我需要它在我ng-view的成功时加载我的部分主页.

这是我试过的:

function loginCtrl($scope, $http, $location){
    $http.post(url,data).success(function(data){
        $location.path('/home');
    });
}
Run Code Online (Sandbox Code Playgroud)

我的网址更改但未ng-view更新的结果.当我手动刷新页面时它会更新.

(已经正确配置了路由$routeProvider,我已经测试过使用独立功能重定向此功能而不是回调功能)

我也尝试定义$location.path('/home')为一个函数,然后在回调上调用它仍然无法正常工作.

我做了一些研究,发现一些文章说明在使用另一个第三方插件时会发生这种情况,我只加载angular.js

对某些学习材料的任何见解或指示都会很棒

Mar*_*dig 83

以下是本文中的changeLocation示例http://www.yearofmoo.com/2012/10/more-angularjs-magic-to-supercharge-your-webapp.html#apply-digest-and-phase

//be sure to inject $scope and $location
var changeLocation = function(url, forceReload) {
  $scope = $scope || angular.element(document).scope();
  if(forceReload || $scope.$$phase) {
    window.location = url;
  }
  else {
    //only use this if you want to replace the history stack
    //$location.path(url).replace();

    //this this if you want to change the URL and add it to the history stack
    $location.path(url);
    $scope.$apply();
  }
};
Run Code Online (Sandbox Code Playgroud)

  • 您应该使用$ window服务而不是直接使用window对象来避免测试时出现问题.http://code.angularjs.org/1.1.5/docs/api/ng.$window (27认同)

0x6*_*C74 14

官方指南中有简单的答案:

它不做什么?

更改浏览器URL时,不会导致整页重新加载.要在更改URL后重新加载页面,请使用较低级别的API $ window.location.href.

来源:https://docs.angularjs.org/guide/$location