How do i correctly use view events in a directive with ionics view caching to reinitialize the directives logic?


I am using a directive that does some initialization logic in its link function

One thing thats done here is listenening to service changes via scope.$watch

How do i correctly remove and readd this $watch if the view is reloaded from cache?


   scope.$on("$destroy", function() {

does not work, the event is never triggered, i therefore can not remove the callback from the watch set previously

what i have so far:

  • the link function is called every time the view enters, automatically, i could store the watch callback somewhere globally/service and remove it in here, not a very nice solution

  • the scope.$on(“destroy”) does not work in a directive, i have no idea why

  • the watches are bound to the directives scope, it doesnt matter if its an isolated scope or not: the watch is never removed

I’ll try to create a codepen, for the time being it would help me to know if theres any way to listen to the view events (enter and beforeEnter) that affect a controller that is bound to a template with the directive in it


i would do the following use ionicView-Events:
set a flag in your controller associated to the view through the ionicView-Events:

$scope.$on("$ionicView.enter", function () {
  $scope.entered = true;
$scope.$on("$ionicView.leave", function () {
  $scope.entered = false;

In the template --> you add a ng-if=“entered” to the dom-elements with your directive
So you need no watcher, because ng-if removes and readds the dom-element --> so your directive gets reinitialised everytime you reenter the view.


I have struggle with this problem for a long time,and I wonder why my “directive” always execute ealier than event(“ionicview.enter”).How can I image to use “ng-if” to controll this order.
thanks buddy!