0

I am stuck with the an issue in which I have to track a time spend by user on particular page and save data in database using mongodb. I have seen one answer about the same but I am confused where to add that piece of code as I am using angularjs. Do I have to keep this code in controller of that particular page or to the index where I am rendering all code using ui-view.

Code from How to measure a time spent on a page?

var start;

$(document).ready(function() {
  start = Date.getTime();

  $(window).unload(function() {
      end = Date.getTime();
      $.ajax({ 
        url: "log.php",
        data: {'timeSpent': end - start}
      })
   });
});

thnx in advance.

Community
  • 1
  • 1

1 Answers1

0

One simple way I can think of to do this is to calculate the total amount of time in seconds spent by the user on a particular page by using the $interval service of angularjs.

First, initialise a $scope variable for the total seconds spent,

$scope.TotalSeconds = 0;

Then, a function to increment the variable,

var IncrementTotalSeconds = function()
{
    $scope.TotalSeconds += 1;
}

After that, use the $interval to increment the variable at every second.

$interval(IncrementTotalSeconds,1000);

Now you have the total seconds spent by the user on that particular page.

You can use the $scope.TotalSeconds to post the total time spent (in seconds) to the database.

Note: You can divide the Total Seconds if you want the time to be Minutes or Hours.

Ernest Soo
  • 194
  • 3
  • 17