4

I am new to angular js and trying to work with ng-view and ngRoute directives.

I have a loginPage.html in which i have code for login button written as follows

<button class="button button-block" ng-click="login()">Log In</button> 

and on clicking the button the login function in loginController will get executed and my controller is written as follows:

var App = angular.module('App', ['ngRoute']);

App.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/', {
        templateUrl: 'loginPage.html',
        controller: 'loginController'
      }).
      when('/home', {
        templateUrl: 'homePage.html',
        controller: 'homeController'
      });
  }]);

App.controller('loginController', ['$scope', '$http', '$location', function($scope, $http) {
    console.log("Hello from login controller");


    $scope.login = function() {
        //console.log($scope.user);
        $http.post('/login', $scope.user).success(function(response) {
            if(response.status == "true")
                //if the response is true i want to go to homepage.html.

            else
                $scope.error="Invalid login! Please try again";
                $scope.user.email="";
                $scope.user.password="";
      });
    };

}]);

If the response.status==true then i want to change my view to /home. Can someone please tell me how to do that?

Thank You.

Minions
  • 1,273
  • 1
  • 11
  • 28

3 Answers3

1

Use $location.path:

if(response.status == "true") {
    $location.path('/home');
}

Also, you have missed adding $location in the controller dependancy list:

function($scope, $http, $location)
Tarun Dugar
  • 8,921
  • 8
  • 42
  • 79
1
if(response.status == "true")
    $location.path("/home");

Don't forget to add $location to your controller parameters like this:

['$scope', '$http', '$location', function($scope, $http, $location)...

Also, wrap your else statement in brackets, or else only the first row is inside the statement:

else {
    $scope.error="Invalid login! Please try again";
    $scope.user.email="";
    $scope.user.password="";
}
henrikmerlander
  • 1,554
  • 13
  • 20
0
if(response.status == "true")
   $location.path("/home");
Mjsa
  • 1