[angularjs] Run a controller function whenever a view is opened/shown

I'm building an app with angular+ionic that uses a classic three-button menu at the bottom with three ion-tabs in it. When a user clicks a tab, that template opens through ui-router.

I have states like this:

$stateProvider
  .state('other', {
    url: "/other",
    abstract: true,
    templateUrl: "templates/other/other.html"
})

In the template I do something like:

<ion-nav-view name="other" ng-init="doSomething()"></ion-nav-view>

I'm aware that I can write the doSomething() function in my controller and just call it manually there. That gives me the same problem though. I can't seem to figure out how to call the doSomething() function more than once, whenever somebody opens that view.

Right now, the doSomething() function gets called just fine, but only the first time that view/tab gets opened by the user. I'd like to call a function (to update geolocation) whenever a user opens that view or tab.

What would be a correct way to implement that?

Thanks for helping out !

This question is related to angularjs ionic-framework

The answer is


Following up on the answer and link from AlexMart, something like this works:

.controller('MyCtrl', function($scope) {
  $scope.$on('$ionicView.enter', function() {
     // Code you want executed every time view is opened
     console.log('Opened!')
  })
})

By default, your controllers were cache and that is why your controller only fired once. To turn off caching for a certain controller you have to modify your .config(..).state and set the cache option to false. eg :

  .state('myApp', {
    cache: false,
    url: "/form",
    views: {
      'menuContent': {
        templateUrl: "templates/form.html",
        controller: 'formCtrl'
      }
    }
  })

for further reading please visit http://ionicframework.com/docs/api/directive/ionNavView/


I had a similar problem with ionic where I was trying to load the native camera as soon as I select the camera tab. I resolved the issue by setting the controller to the ion-view component for the camera tab (in tabs.html) and then calling the $scope method that loads my camera (addImage).

In www/templates/tabs.html

  <ion-tab title="Camera" icon-off="ion-camera" icon-on="ion-camera" href="#/tab/chats" ng-controller="AddMediaCtrl" ng-click="addImage()">
    <ion-nav-view  name="tab-chats"></ion-nav-view>
  </ion-tab>

The addImage method, defined in AddMediaCtrl loads the native camera every time the user clicks the "Camera" tab. I did not have to change anything in the angular cache for this to work. I hope this helps.


Why don't you disable the view cache with cache-view="false"?

In your view add this to the ion-nav-view like that:

<ion-nav-view name="other" cache-view="false"></ion-nav-view>

Or in your stateProvider:

$stateProvider.state('other', {
   cache: false,
   url : '/other',
   templateUrl : 'templates/other/other.html'
})

Either one will make your controller being called always.


I faced at the same problem, and here i leave the reason of this behavior for everyone else with the same issue.

View LifeCycle

In order to improve performance, we've improved Ionic's ability to cache view elements and scope data. Once a controller is initialized, it may persist throughout the app’s life; it’s just hidden and removed from the watch cycle. Since we aren’t rebuilding scope, we’ve added events for which we should listen when entering the watch cycle again.

To see full description and $ionicView events go to: http://ionicframework.com/blog/navigating-the-changes/


Considering Ionic's ability to cache view elements and scope data mentioned above, this might be another way of doing, if you want to run the controller every time the view gets loaded. You can globally disable the caching mechanism used by ionic by doing:

$ionicConfigProvider.views.maxCache(0);

Else, the way I had it working for me was doing

$scope.$on("$ionicView.afterLeave", function () {
     $ionicHistory.clearCache();
}); 

This is to clear the cache before leaving the view to re-run controller every time you enter back again.


This is probably what you were looking for:

Ionic caches your views and thus your controllers by default (max of 10) http://ionicframework.com/docs/api/directive/ionView/

There are events you can hook onto to let your controller do certain things based on those ionic events. see here for an example: http://ionicframework.com/blog/navigating-the-changes/


For example to @Michael Trouw,

inside your controller put this code. this will run everytime when this state is entered or active, you do not need to worry about disabling cache and it's a better approach.

.controller('exampleCtrl',function($scope){
$scope.$on('$ionicView.enter', function(){
        // Any thing you can think of
        alert("This function just ran away");   
    });
})

You can have more examples of flexibility like $ionicView.beforeEnter -> which runs before a view is shown. And there are some more to it.


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 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