I have an Ionic app where I want the controller to reload whenever a user visits a tab. I have the following link here...
<ion-tab icon-off="ion-ios-person-outline" icon-on="ion-ios-person" ui-sref="tab.profile({reload: true})">
<ion-nav-view name="tab-profile"></ion-nav-view>
</ion-tab>
If I visit the tab link once, the controller loads(obviously). If I leave the page and click that same link again the page does not reload. The way I'm detecting this page reload by injecting a console.log
into the controller file.
angular.module('coolsite.user')
.controller('ProfileController', profileController)
profileController.$inject = [];
function profileController( ) {
var vm = this;
console.log("activated");
}
How do I reload the controller every time the user clicks on the link?
You should use transitionTo
to reload your controller & route.
Markup
<ion-tab icon-off="ion-ios-person-outline" icon-on="ion-ios-person" ng-click="vm.redirect('tab.profile')">
<ion-nav-view name="tab-profile"></ion-nav-view>
</ion-tab>
Controller
vm.redirect = function(stateName){
$state.transitionTo(stateName, {} , {
reload: true,
inherit: false,
notify: true
});
}
Update
Though it was not related to angular-ui-router
Its specifically related to ionic-view
, they getting cached by default. You need can disable those caching by state just by mentioning cache: false
.
Code
.state('tab.profile', {
url: '/profile',
views: {
'tab-profile': {
templateUrl: 'templates/tabs/profile.html',
controller: 'ProfileController as profile',
reload: true
}
},
cache: false
})
There are also two alternative way to achieve this, you can find it in this answer with better explanation which is given by me only
So, I think what you're really looking to do is not use the cache. That means that in your state, you'll want to set cache: false
. To be clear, controllers are not "reloaded." The scope is simple removed and re-added when you return to the page, unless you set the cache to false.
I don't think that's necessarily the best approach though. I would use the events in the navigation lifecycle and set up a handler for $ionicView.loaded
instead. You can find details about the event for ion-view in the doc under the section: View LifeCycle and Events.