Chinu Chinu - 4 months ago 73
AngularJS Question

AngularJS logout not working

I have tried logout my current session. But logout not working. Check below my code:

view

<a ui-sref="logout">
<i class="fa fa-sign-out"></i> Log out
</a>


config.js

$stateProvider
.state('logout', {
url: "/logout",
templateUrl: '',
controller: "LogoutController"
});


controllers.js

function LogoutController($location, $http) {
alert("hi");
//Session.clear();
var request = $http({
method: "post",
url: "users/ajaxLogout",
dataType: 'json',
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
request.success(function(data) {

});
$location.path('/login');
}

angular
.module('inspinia')
.controller('MainCtrl', MainCtrl)
.controller('LogoutController', LogoutController);


I have alerted in
LogoutController
but that function not calling while I am clicking
Log out
link.

I follow this link - Angular - Logout redirect route Please check and let me know where is error in my code.

Answer

Put the logout code inside a function in your controller:

function LogoutController($location, $http, $scope) {

    this.logout = function() {
        alert("hi");
        //Session.clear();
        var request = $http({
            method: "post",
            url: "users/ajaxLogout",
            dataType: 'json',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        });
        request.success(function(data) {
            $location.path('/login');
        });

    }
}

And then call the function on clicking the logout link by using ng-click:

<div ng-controller="LogoutController as ctrl">
<a ui-sref="logout">
   <i class="fa fa-sign-out" ng-click="ctrl.logout()"></i> Log out
</a>
</div>