-2
$scope.saveStats = function () {
  $http({
    method: "post",
    url: "save.php",
    data: $scope.info
  }).success(function () {
    console.log($scope.info);
  })
};

window.onbeforeunload = $scope.saveStats();

This code is not doing what I expect it to do. It just fires saveStats() when loading the page. And when I exit the page, it does not fire saveStats().

I wrote this inside my angular controller. I'm pretty confused at the result...

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
brucelee
  • 147
  • 2
  • 11
  • What does `x = foo();` do? Right! So that's exactly what `window.onbeforeunload = $scope.saveStats();` does. – T.J. Crowder Jun 08 '15 at 12:12
  • 1
    possible duplicate of [Why does click event handler fire immediately upon page load?](http://stackoverflow.com/questions/7102413/why-does-click-event-handler-fire-immediately-upon-page-load) – Qantas 94 Heavy Jun 08 '15 at 12:16

2 Answers2

4
window.onbeforeunload = $scope.saveStats();
                                        ^^^

By adding () to the end of saveStats, you're executing the function immediately. What you want to do is pass a reference to saveStats to your onbeforeunload like this:

window.onbeforeunload = $scope.saveStats;
CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
  • 1
    Depends on whether `saveStats` needs `this` to be `$scope`; if it does, you'll need a `bind`. – T.J. Crowder Jun 08 '15 at 12:13
  • @T.J.Crowder Good point to highlight, but the code provided doesn't use `this` – CodingIntrigue Jun 08 '15 at 12:14
  • 1
    DAMNIT, that was a lame mistake. Thank you for taking the time and clearing it up in such a great way. -- I have to wait a bit before I'm allowed to accept this as the answer – brucelee Jun 08 '15 at 12:20
0

Try this:

 window.onbeforeunload = $scope.saveStats;

You are just trying to pass the function by reference, not executing it, so remove the double brackets that trigger the function.

somethinghere
  • 16,311
  • 2
  • 28
  • 42