0

In my AngularJS app, I'd like to create a timer, sothat user is redirected from any page off my app to the landing page, if he's idle for 10 seconds.

To do this, I created necessary timer functions in an controller:

.controller('LandingCtrl', ['$scope', '$rootScope', '$timeout', '$state',
                                function($scope, $rootScope, $timeout, $state) {

    $rootScope.new_timer = function() {
      $rootScope.mytimer = $timeout(function() {
        $rootScope.$broadcast("timeover");
        console.log("timeover event sent");
        }, 10000);
    }

    $rootScope.cancel_timer = function() {
      $timeout.cancel($rootScope.mytimer);
    }

    $rootScope.raz_timer = function() {
      $rootScope.cancel_timer();
      $rootScope.new_timer();
    }

}])

Then, in every other controllers, I add something like:

$scope.$on("timeover", function() {
  $state.go('Landing');
})

Now, the only missing thing is to create a global event listener that would use the raz_timer() function when a user touch the screen of the app. Any idea how to do this?

Note : I'm using Ionic Framework on top of AngularJS, and app is used throw a mobile device, not a desktop (I guess this could be usefull to know what event to pick).

David Dahan
  • 10,576
  • 11
  • 64
  • 137
  • I know that this is anti pattern, but you can try use the digest cycle for that (If angular not do digest mean the user is idle). something like this in the run app let redirect = _.debounce(redirect, 10000); $rootScope.$watch(() => setTimeOut(() => redirect()), 1);. – Jesús Quintana Sep 10 '15 at 10:02
  • Please refer to [enter link description here][1] [1]: http://stackoverflow.com/questions/19446755/on-and-broadcast-in-angular This may help you. – Omkara Sep 10 '15 at 10:03
  • you can check this page: Using The Scope Tree As A Publish And Subscribe (Pub/Sub) Mechanism In AngularJS - http://www.bennadel.com/blog/2734-using-the-scope-tree-as-a-publish-and-subscribe-pub-sub-mechanism-in-angularjs.htm – macrog Sep 10 '15 at 10:10
  • @Omkara, this helped for using `$scope` instead of `$rootScope` in controllers that listen to the event. Thanks. However, nothing about a global event listener ? – David Dahan Sep 10 '15 at 10:16
  • @macrog interesting article for building a full pub/sub system. However I think it's a little bit overkill for myself. Plus, I may be wrong but I didn't see anything about catching touch events. Instead of going from scracth, I'd like (if possible) to add the missing code only. Thanks. – David Dahan Sep 10 '15 at 10:22

0 Answers0