How to redirect to other page after successful login in angularjs?

Niranjan Godbole picture Niranjan Godbole · Feb 7, 2017 · Viewed 11.4k times · Source

Hi I am developing one application in angularjs as front end and web api2 as backend. I am new to both angular and web api. I have completed login page in angularjs. As soon as my login successful i want to go to page called Index.cshtml located at Views/Home/index.cshtml. I am trying as below.

This is my controller code.

app.controller('Login', function ($scope, LoginService) {
    $scope.Login = function () {
        var sub = {
            User_Name: $scope.User_Name,
            User_Password: $scope.User_Password
        };
        var checkData = LoginService.Login(sub);
        checkData.then(function (data) {
            //want redirection
            var url = '/Home/Index/';
            window.location = url;
            }, function (error) {
            })
        };
});

This is my module.js

var app;
(function () {
    app = angular.module("Login", []);
})();

service.js

app.service("LoginService", function ($http) {
    this.Login = function (sub) {
        var credentials = { User_Name: sub.User_Name, User_Password: sub.User_Password };
           $http.post('api/NCT_UsersLogin/', credentials).success(function (response) {  });
    }
});

I am trying using window.location but it is not working. May I get some help here? Any help would be appreciated. Thank you.

Answer

Saurabh Agrawal picture Saurabh Agrawal · Feb 7, 2017

You can use $state.go(url)

Try this

app.controller('Login', function ($scope, LoginService, $state) {
    $scope.Login = function () {
        var sub = {
            User_Name: $scope.User_Name,
            User_Password: $scope.User_Password
        };
        var checkData = LoginService.Login(sub);
        checkData.then(function (data) {
            //want redirection
            var url = '/Home/Index/';
            $state.go(url);
            }, function (error) {
            })
        };

});