1

Want to calculate time spent on each state separately in AngularJS routing. I'm using ui-router.

RAMESHKUMAR
  • 316
  • 4
  • 11

1 Answers1

1

you can get is using the time difference between previous route change and current route change... hook into $stateChangeSuccess event onto $rootScope,

the code would similar to below ( add it in your root-controller // app level controller)

     var timeStart;

     $rootScope.$on('$stateChangeSuccess', function(current, prev){
            if(angular.isUndefined(timeStart)){
                 $log.info('this is the first route')
            } else {
                 var timeSpent = moment().diff(timeStart).format('mm:ss');
                 $log.info(`total time spent ${timeSpent} route ${prev.name}`);
                 timeStart = moment();
            }
     })

** EDIT **

it is using momentjs, you can use any date library for date manipulation/getting time difference, read here on how to do it

Community
  • 1
  • 1
harishr
  • 17,807
  • 9
  • 78
  • 125
  • good answer, but you are using `momentjs` functionality here and PO hasn't asked the solution with `momentjs`. You should've mentioned in the answer here. +1 for the solution although. It adds something good to the post. – Paritosh Sep 22 '16 at 05:15
  • @entre, is there any solution without using momentjs – RAMESHKUMAR Sep 22 '16 at 05:27
  • please go thru the link in edit, to find out how to do date manipulation using core javascript date object – harishr Sep 22 '16 at 06:13