Ionic: method call on page enter

I have

  <ion-side-menu> 
with links to my pages defined here:
app.config(function($stateProvider, $urlRouterProvider, $ionicConfigProvider) { $stateProvider.state('content', { url: "/content", abstract: true, templateUrl: "templates/sidemenu.html", controller: 'SideController' }); $stateProvider.state('content.home', { url: "/home", views: { 'menuContent': { templateUrl: "templates/home.html", controller: "HomeController" } } }); $stateProvider.state('content.nearby', { url: "/nearby", views: { 'menuContent': { templateUrl: "templates/nearby.html", controller: "NearbyController" } } }); $stateProvider.state('content.map', { url: "/map", views: { 'menuContent': { templateUrl: "templates/map.html", controller: "MapController" } } }); $stateProvider.state('content.radar', { url: "/radar", views: { 'menuContent': { templateUrl: "templates/radar.html", controller: "RadarController" } } }); $stateProvider.state('content.location-details', { url: "/location-details/:index", views: { 'menuContent': { templateUrl: "templates/location-details.html", controller: "DetailsController" } }, resolve: { currentLocation: function($stateParams, shareService, NearbyFactory) { return NearbyFactory.getLocations()[$stateParams.index]; } } }); $urlRouterProvider.otherwise("/content/home"); }); 

I want to execute the method in my controllers when the user goes to this page and when the page is left (to load AJAX data or start listening to some Cordoba sensors). Like this:

  app.controller("HomeController", function() { $scope.onEnter = function(previous_page) { ... }; $scope.onExit = function(next_page) { ... }; }); 

I already tried OnEnter and onExit inside the state of $ stateProvider, but afaik I don't have my $ scope.

What is the easiest / best / best way to get this functionality? It would be great if I could define the previous / next page, and if the user moved back / forward. I tried this:

 $scope.$on('$routeChangeStart', function(event, next, current) { console.log(next); }); 

but it didn’t work every time, and it didn’t work when the page loaded. It also seems a little dirty to me, because I have to implement this in each individual controller.

Thanks!

+7
angularjs navigation angular-ui-router ionic
source share
2 answers

You can use $ ionicView.beforeEnter and beforeLeave. Just add this to your HomeController:

  app.controller("HomeController", function() { $scope.$on('$ionicView.beforeEnter', function() { //do stuff before enter }); $scope.$on('$ionicView.beforeLeave', function() { //do your stuff after leaving }); }); 

You can check the $ ionicView docs here .

+6
source share

You can try this. It works every time the page loads:

 $scope.$on('$locationChangeStart', function(event) { console.log(event); }); 
0
source share

All Articles