Aletz Morgan Aletz Morgan - 25 days ago 8
Javascript Question

on enter controller call function angularJS

The problem is that i need to call a function every single time that a route change to a specific state, lets say i have chatController and i have to fire a() every second but if i exit the controller i have to stop a() and when i'm back to chatController i have to restart a()

My code:

$scope.stop = $interval(yourOperation, 1000);

var dereg = $rootScope.$on('$locationChangeSuccess', function() {
$interval.cancel($scope.stop);
dereg();
});


function yourOperation() {
console.log('$location', $location.$$url)
console.log('test');
}


Works fine executing every single and stops when the controller change, but it doesn't work anymore if i go back, i tried with ng-init() function but only fires the first time that the controller start, i need it always when i'm on a specifict controller.

Answer

1] If it is state then you can use following event to call function every time when you back to state

$scope.$on('$ionicView.enter',function(){       
      $scope.callingFunctionName(); 
});

Here you may need to add following attribute in app.js state declaration

cache: false

2] In case you are using modal then controller will automatically get initialize.

just need to call function like following -

$scope.callingFunctionName(); 

Hope this will help you.

Comments