Giovanni
Giovanni

Reputation: 425

Cordova Ionic refresh side menu after log in and log out

I'm trying to automatically reload my side menu after I log in and log out. I'm doing that by checking my window.localStorage. I've experienced that the side menu won't reload/refresh after I do the action login or logout.

I'm using $state.go('tabs.home') to navigate to another page, but my side menu won't refresh.

Below here is my code:

navCtrl:

app.controller('NavCtrl', function ($scope, $ionicSideMenuDelegate, $rootScope) {
    $scope.showMenu = function () {
        $ionicSideMenuDelegate.toggleLeft();
    };
    $scope.showRightMenu = function () {
        $ionicSideMenuDelegate.toggleRight();
    };

    var data = JSON.parse(window.localStorage.getItem("currentUserData"));
    if (data != null) {
        if (data["id_gebruiker"] == null) {
            $rootScope.control = {
                showLogin: false,
                showLogout: true
            };
        }
        else {
            $rootScope.control = {
                showLogin: true,
                showLogout: false
            };
        }

    }

})

navHtml:

<ion-side-menu-content ng-controller="NavCtrl">
          <ion-nav-bar class="bar-positive">
            <ion-nav-back-button class="button-icon ion-arrow-left-c">
            </ion-nav-back-button>

            <ion-nav-buttons side="left">
              <button class="button button-icon button-clear ion-navicon" ng-click="showMenu()">
              </button>
            </ion-nav-buttons>

            <ion-nav-buttons side="right">
              <button class="button button-icon button-clear ion-ios7-gear" ng-click="showRightMenu()">
              </button>
            </ion-nav-buttons>
          </ion-nav-bar>
          <ion-nav-view animation="slide-left-right"></ion-nav-view>
        </ion-side-menu-content> 

loginCtrl:

app.controller('LoginCtrl', function ($scope, $http, $state) {
    /*
    * This method will be called on click event of button.
    * Here we will read the email and password value and call our PHP file.
    */

    $scope.check_credentials = function () {

        //document.getElementById("message").textContent = "";

        $http({ method: 'GET', url: 'http://localhost:34912/api/gebruikers?email=' + $scope.email + '&wachtwoord=' + $scope.wachtwoord }).success(function (data) {
            bindUserData(data);
            //window.location.reload();

            $state.go('tabs.about');
        });

        function bindUserData(data) {
            //alert(JSON.stringify(data));
            window.localStorage.setItem("currentUserData", JSON.stringify(data));
        }
    }
});

app.controller('LogoutCtrl', function ($scope, $http, $state) {
    /*
    * This method will be called on click event of button.
    * Here we will read the email and password value and call our PHP file.
    */

    $scope.logout = function () {

        var data = JSON.parse(window.localStorage.getItem("currentUserData"));
        if (data != null) {
            window.localStorage.removeItem("currentUserData");
            $state.go('tabs.home');
        }
    }
});

loginHtml:

<ion-view title="Login">
    <ion-content>
        <form id="loginForm" ng-app="ionicApp" ng-controller="LoginCtrl">
            <div class="list">
                <label class="item item-input">
                    <span class="input-label">Email</span>
                    <input ng-model="email" type="text" placeholder="Username" />
                </label>

                <label class="item item-input">
                    <span class="input-label">Wachtwoord</span>
                    <input ng-model="wachtwoord" type="password" placeholder="***********" />
                </label>
            </div>
            <div class="padding">
                <input type="submit" value="Log on" ng-click="check_credentials()" class="button button-block button-positive" />
            </div>
        </form>
    </ion-content>

I hope you'll understand my problem. I also tried to do a window.location.reload() before $state.go, but that looks buggy. Are there some best practices to fix my problem? Please help me!

Greetings.

Upvotes: 4

Views: 8055

Answers (2)

Look at the accepted solution at https://stackoverflow.com/a/30524540/1376640

Relevant part of the code is:

$scope.logout = function () {
    $ionicLoading.show({
        template: 'Logging out....'
    });
    $localstorage.set('loggin_state', '');

    $timeout(function () {
        $ionicLoading.hide();
        $ionicHistory.clearCache();
        $ionicHistory.clearHistory();
        $ionicHistory.nextViewOptions({
            disableBack: true,
            historyRoot: true
        });
        $state.go('login');
    }, 30);

};

Worked for me.

Upvotes: 4

user963433
user963433

Reputation: 11

Not a Angular expert but I think that your page will have rebuilt before the $http.get has finished. I got round this by raising an event so where you call bindUserData in the get success change that to $scope.$emit('event', data) then handle the update in a $scope.$on('event'. data). Cut down version of my code below.

controller('AppCtrl', function($scope, $ionicModal, $timeout, MenuData, Data, $ionicActionSheet, UserData, $state, SessionStorage) {

$scope.$on('menuDataChange', function (event, data) {
    //refresh menu items data
    $scope.items = data;

    //clear the state
    $state.go($state.current, {}, { reload: true });
});

$scope.items = Data.getItems(SessionStorage.isAuthenticated());

// Form data for the login modal
$scope.loginData = {};

$scope.doLogout = function () {
    SessionStorage.clear();

    $scope.$emit('menuDataChange', Data.getItems(false));  //Get the menu items for unauthenticated users and raise the change event
};

// Perform the login action when the user submits the login form
$scope.doLogin = function () {
    console.log('Doing login', $scope.loginData);

    UserData.async($scope.loginData.username, $scope.loginData.password, '12345').then(
        // successCallback
        function () {

            data = UserData.getAll();

            var expirationDate = new Date();
            expirationDate.setTime(new Date().getTime() + 1200000); //20 minutes

            SessionStorage.save({ serverAuthToken: data.d.Items[0].ServerAuthToken, expirationDate: expirationDate });

            $scope.$emit('menuDataChange', Data.getItems(true));  //get the menu items for authenticated users and raise the change event

            console.log(data);

            $state.go('app.home', {}, { reload: true });
        },
        // errorCallback 
        function () {
            console.log('userdate error');

        },
        // notifyCallback
        function () { }
    );

};

})

Upvotes: 1

Related Questions