doonot doonot - 3 months ago 19
AngularJS Question

How can I call a function in Ionic when a view is entered?

I have a profile page that lists the users profile. The user can click an edit button to edit all user related information. Once the user saved the page, they navigate back to the profile page that should ideally be updated automatically.

Now I am missing kind of an event that triggers, when a user navigates to a page.

window.onLoad()
does only work once, same for
window.onPageShow()
.
window.onPopState()
is triggered when the user goes away from the page.

My idea was to rely on such an event, then call $scope.init() which downloads the user information and sets it to the view:

.controller('UserProfileCtrl', function($scope, $http, $window, LocationService) {
$window.onPageShow = function() {
console.log("UserProfileCtrl->onPageShow(), getting location and loading user.");
LocationService.getLocation();
$scope.init();
};

$scope.init = function() {
$http.post("my-backend-address")
.success(function (data, status, headers, config) {
$scope.user = data.user;
})
}
});

Answer

In Ionic you have something called View Events, you can read about them here. There are two events of interest for your use case: $ionicView.loaded and $ionicView.beforeEnter.

Here is a code example of how you could use it with your code:

$scope.$on("$ionicView.beforeEnter", function() {
   console.log("UserProfileCtrl->onPageShow(), getting location and loading user.");
  LocationService.getLocation();
  $scope.init();
});

In short, $ionicView.loaded is called when the view is created and $ionicView.beforeEnter is called every time the view is about to be entered. I would recommend to try $ionicView.beforeEnter to see whether it fits your use case.

Comments