[angularjs] Clear History and Reload Page on Login/Logout Using Ionic Framework

I am new to mobile application development with Ionic. On login and logout I need to reload the page, in order to refresh the data, however, $state.go('mainPage') takes the user back to the view without reloading - the controller behind it is never invoked.

Is there a way to clear history and reload the state in Ionic?

This question is related to angularjs angular-ui-router ionic-framework

The answer is


I have found a solution which helped me to get it done. Setting cache-view="false" on ion-view tag resolved my problem.

<ion-view cache-view="false" view-title="My Title!">
  ....
</ion-view>

As pointed out by @ezain reload controllers only when its necessary. Another cleaner way of updating data when changing states rather than reloading the controller is using broadcast events and listening to such events in controllers that need to update data on views.

Example: in your login/logout functions you can do something like so:

$scope.login = function(){
    //After login logic then send a broadcast
    $rootScope.$broadcast("user-logged-in");
    $state.go("mainPage");
};
$scope.logout = function(){
   //After logout logic then send a broadcast
   $rootScope.$broadcast("user-logged-out");
   $state.go("mainPage");
};

Now in your mainPage controller trigger the changes in the view by using the $on function to listen to broadcast within the mainPage Controller like so:

$scope.$on("user-logged-in", function(){
     //update mainPage view data here eg. $scope.username = 'John';
});

$scope.$on("user-logged-out", function(){
    //update mainPage view data here eg. $scope.username = '';
});

I tried many methods, but found this method is absolutely correct:

$window.location.reload();

Hope this help others stuck for days like me with version: angular 1.5.5, ionic 1.2.4, angular-ui-router 1.0.0


I needed to reload the state to make scrollbars work. They did not work when coming through another state - 'registration'. If the app was force closed after registration and opened again, i.e. it went directly to 'home' state, the scrollbars worked. None of the above solutions worked.

When after registration, I replaced:

$state.go("home");

with

window.location = "index.html"; 

The app reloaded, and the scrollbars worked.


.state(url: '/url', controller: Ctl, templateUrl: 'template.html', cache: false) cache: false ==> solved my problem !


I found that JimTheDev's answer only worked when the state definition had cache:false set. With the view cached, you can do $ionicHistory.clearCache() and then $state.go('app.fooDestinationView') if you're navigating from one state to the one that is cached but needs refreshing.

See my answer here as it requires a simple change to Ionic and I created a pull request: https://stackoverflow.com/a/30224972/756177


Reload the page isn't the best approach.

you can handle state change events for reload data without reload the view itself.

read about ionicView life-cycle here:

http://blog.ionic.io/navigating-the-changes/

and handle the event beforeEnter for data reload.

$scope.$on('$ionicView.beforeEnter', function(){
  // Any thing you can think of
});

If you want to reload after view change you need to

$state.reload('state',{reload:true});

If you want to make that view the new "root", you can tell ionic that the next view it's gonna be the root

 $ionicHistory.nextViewOptions({ historyRoot: true });
 $state.go('app.xxx');
 return;

If you want to make your controllers reload after each view change

app.config(function ($stateProvider, $urlRouterProvider, $ionicConfigProvider) {

$ionicConfigProvider.views.maxCache(0);

The controller is called only once, and you SHOULD preserve this logic model, what I usually do is:

I create a method $scope.reload(params)

At the beginning of this method I call $ionicLoading.show({template:..}) to show my custom spinner

When may reload process is finished, I can call $ionicLoading.hide() as a callback

Finally, Inside the button REFRESH, I add ng-click = "reload(params)"

The only downside of this solution is that you lose the ionic navigation history system

Hope this helps!


The correct answer:

$window.location.reload(true);

I was trying to do refresh page using angularjs when i saw websites i got confused but no code was working for the code then i got solution for reloading page using

$state.go('path',null,{reload:true});

use this in a function this will work.


None of the solutions mentioned above worked for a hostname that is different from localhost!

I had to add notify: false to the list of options that I pass to $state.go, to avoid calling Angular change listeners, before $window.location.reload call gets called. Final code looks like:

$state.go('home', {}, {reload: true, notify: false});

>>> EDIT - $timeout might be necessary depending on your browser >>>

$timeout(function () { $window.location.reload(true); }, 100);

<<< END OF EDIT <<<

More about this on ui-router reference.


In my case I need to clear just the view and restart the controller. I could get my intention with this snippet:

$ionicHistory.clearCache([$state.current.name]).then(function() {
  $state.reload();
}

The cache still working and seems that just the view is cleared.

ionic --version says 1.7.5.


Examples related to angularjs

AngularJs directive not updating another directive's scope ERROR in Cannot find module 'node-sass' CORS: credentials mode is 'include' CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 Print Html template in Angular 2 (ng-print in Angular 2) $http.get(...).success is not a function Angular 1.6.0: "Possibly unhandled rejection" error Find object by its property in array of objects with AngularJS way Error: Cannot invoke an expression whose type lacks a call signature

Examples related to angular-ui-router

how to refresh page in angular 2 Could not resolve '...' from state '' AngularJS ui router passing data between states without URL What is the difference between $routeProvider and $stateProvider? How to pass parameters using ui-sref in ui-router to controller Exposing the current state name with ui router Clear History and Reload Page on Login/Logout Using Ionic Framework Using $window or $location to Redirect in AngularJS AngularJS UI Router - change url without reloading state `ui-router` $stateParams vs. $state.params

Examples related to ionic-framework

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory in ionic 3 Xcode couldn't find any provisioning profiles matching No provider for Http StaticInjectorError Error: Cannot find module '../lib/utils/unsupported.js' while using Ionic Error: Could not find gradle wrapper within Android SDK. Might need to update your Android SDK - Android Ionic 2: Cordova is not available. Make sure to include cordova.js or run in a device/simulator (running in emulator) Error: Node Sass does not yet support your current environment: Windows 64-bit with false Failed to find 'ANDROID_HOME' environment variable Ionic android build Error - Failed to find 'ANDROID_HOME' environment variable ionic build Android | error: No installed build tools found. Please install the Android build tools