Tutorialsplane

Ionic run a controller function on view open/shown


Ionic run a controller function on view open/shown : We sometimes need to call a controller when the view is loded or open/shown. You can load the controller on the ion-nav-view load and it’s function. Here in this tutorial we are going to explain how to load and call a different controller function whenever the view is loaded ie. open/shown.


Ionic run a controller function on view open/shown

Here are the steps to run a controller function on ion view open-

ion-nav-view Part

Add the controller name you want to load and call it’s function as below

Ionic run a controller function on view open/shown:

<ion-nav-view ng-controller="myController" name="test" ng-init="testFunction()">

</ion-nav-view>

Now let us define the controller and it’s function as below-

Controller Part

Ionic run a controller function on view open/shown:

.controller('myController', function($scope) {
  $scope.testFunction = function() {    
	 //Your Code Goes Here
  };
  
});

The above controller will be loaded and function testFunction will be called.

Note : Cache may cause issue sometimes so if you face this problem clear cache each time it is loaded or each time before closing the view.

Ionic clear view cache on close : afterLeave –

Ionic clear view cache on close : afterLeave –

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

The above example will clear ionic view cache each time it is closed.

Ionic FAQ