angularjsng-idle

Better way of implementing config for a custom directive (ngIdle)?


For those of you unfamiliar, ngIdle can be found here.

It's basically a way to make an idle timeout like many banks have on their websites using angular.

It works great, however the way that I am currently using it is by placing some of the config stuff in my controller. The problem is I am working with multiple controllers and don't really want to just copy paste this config stuff throughout my project.

Here is what the config looks like:

function closeModals()
    {           
      // Function closes any modals that are currently open (used when coming back from idle)
      if ($scope.warning) {
        $scope.warning.close();
        $scope.warning = null;
      }
      if ($scope.timedout) {
        $scope.timedout.close();
        $scope.timedout = null;
      }
    }

    $scope.$on('IdleStart', function () {   // What happens when the user goes idle (idle time is defined in app.js IdleProvider config)
      closeModals();
      $scope.warning = $modal.open({
        templateUrl: 'views/timeoutModal.html',
        windowClass: 'modal-danger'
      });
    });

    $scope.$on('IdleTimeout', function () { // This is what happens when the user waits passed the warning timer
      logout();
      closeModals();
      Idle.unwatch();
      $scope.$apply();
      alert("You have been signed out due to inactivity.");
    });

    $scope.$on('IdleEnd', function () { // What happens when the user comes back from being idle but before they are timed out
      closeModals();
      $scope.amIdle = false;
    });

Basically, I want to be able to simply tell my controller that I want to use these configuration settings and it would be able to use them without needing to put them in the controller.


Solution

  • You should not need this config in multiple places. Looking at NgIdle they are broadcasting the event from the $rootScope. https://github.com/HackedByChinese/ng-idle/blob/develop/angular-idle.js#L193

    The only reason you would need to setup watched on different scopes because you wanted to do multiple things for a specific event.

    All you need to do is in a single controller inject $rootScope and add the event watchers to that.