72

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

sudo bangbang
  • 27,127
  • 11
  • 75
  • 77
George Ananda Eman
  • 3,292
  • 8
  • 28
  • 29
  • what do you mean by ng-view? also, does $location.path() internally call window.location = ...? – Verdagon Jan 13 '13 at 07:32
  • 1
    I forgot to mention this is within the context of using angularjs framework. - edited the above – George Ananda Eman Jan 13 '13 at 07:51
  • Interesting! Do you use firebug or something like that? Does your app make a request for a partial, when a route is changed? – theotheo Jan 13 '13 at 18:40
  • Try calling $rootScope.$apply() after the $location.path('/home'). – matys84pl Jan 13 '13 at 19:29
  • @user1248256 yes it does `.when('/home', {templateUrl:'partials/home.html',controller: myCtrl})`. i am using chrome's developer tools, and it doesnt show a request to home.html. – George Ananda Eman Jan 13 '13 at 20:22
  • @GeorgeAnandaEman, let's try to make unsuccessful request and then change location on error callback. something like that: ```$http.post('\itdoesnotexist',data).error(function($location.path('/home');});``` the partial would be downloaded? – theotheo Jan 13 '13 at 21:55
  • 1
    @GeorgeAnandaEman, btw, did you see this thread: http://stackoverflow.com/questions/11784656/angularjs-location-not-changing-the-path? i bet "yes", but just in case. – theotheo Jan 13 '13 at 22:15
  • @user1248256 will look it up and try your test asap – George Ananda Eman Jan 15 '13 at 08:57

6 Answers6

83

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();
  }
};
Mark Nadig
  • 4,901
  • 4
  • 37
  • 46
  • 27
    You should probably use the $window service instead of directly using the window object to avoid issues when testing. http://code.angularjs.org/1.1.5/docs/api/ng.$window – Justin Aug 15 '13 at 19:44
  • 1
    A single out-of-function answer: Use $window.location = url; – Joao Polo May 11 '15 at 12:33
  • i have also written a seperate back history stack – Siddharth Apr 25 '16 at 15:15
  • app.directive("backButton", function ($window) { return { restrict: "A", link: function (scope, elem, attrs) { elem.bind("click", function () { $window.history.back(); }); } }; }); – Siddharth Apr 25 '16 at 15:15
14

There is simple answer in the official guide:

What does it not do?

It does not cause a full page reload when the browser URL is changed. To reload the page after changing the URL, use the lower-level API, $window.location.href.

Source: https://docs.angularjs.org/guide/$location

reto
  • 9,995
  • 5
  • 53
  • 52
0x6B6F77616C74
  • 2,559
  • 7
  • 38
  • 65
3

I am doing the below for page redirection(from login to home page). I have to pass the user object also to the home page. so, i am using windows localstorage.

    $http({
        url:'/login/user',
        method : 'POST',
        headers: {
            'Content-Type': 'application/json'
          },
        data: userData
    }).success(function(loginDetails){
        $scope.updLoginDetails = loginDetails;
        if($scope.updLoginDetails.successful == true)
            {
                loginDetails.custId = $scope.updLoginDetails.customerDetails.cust_ID;
                loginDetails.userName = $scope.updLoginDetails.customerDetails.cust_NM;
                window.localStorage.setItem("loginDetails", JSON.stringify(loginDetails));
                $window.location='/login/homepage';
            }
        else
        alert('No access available.');

    }).error(function(err,status){
        alert('No access available.');      
    });

And it worked for me.

Luca
  • 9,259
  • 5
  • 46
  • 59
user2230867
  • 93
  • 1
  • 3
2

Instead of using success, I change it to then and it works.

here is the code:

lgrg.controller('login', function($scope, $window, $http) {
    $scope.loginUser = {};

    $scope.submitForm = function() {
        $scope.errorInfo = null

        $http({
            method  : 'POST',
            url     : '/login',
            headers : {'Content-Type': 'application/json'}
            data: $scope.loginUser
        }).then(function(data) {
            if (!data.status) {
                $scope.errorInfo = data.info
            } else {
                //page jump
                $window.location.href = '/admin';
            }
        });
    };
});
jcguo
  • 61
  • 1
  • 4
1

Use : $window.location.href = '/Home.html';

0

it's very easy code .. but hard to fined..

detailsApp.controller("SchoolCtrl", function ($scope, $location) { 
      $scope.addSchool = function () {

        location.href='/ManageSchool/TeacherProfile?ID=' + $scope.TeacherID;
      }
});
isanka thalagala
  • 456
  • 2
  • 10
  • 22