In Angular, how to redirect with $location.path as $http.post success callback

George Ananda Eman picture George Ananda Eman · Jan 13, 2013 · Viewed 200.9k times · Source

I am attempting to make a simple authentication service by sending a Post to a php file, I need it to load the home page partial on my ng-view when its successful.

This is what I tried :

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

Results in my url changing but ng-view not updating. It updates when I manually refresh the page.

(routes have been configured properly at the $routeProvider, I have tested redirecting this with a standalone function not as a callback and it works )

I have also tried defining $location.path('/home') as a function and then calling it on the callback it still doesn't work.

I did some research and found some articles stating this happens when using another third party plugin, I am only loading angular.js

Any insights or pointers to some study material will be great

Answer

Mark Nadig picture Mark Nadig · Jan 17, 2013

Here is the changeLocation example from this article 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();
  }
};