2

How do i found out for how much time the button is hold; ie, How do i find the difference between mousedown and mouseup event in angular. I am very new to Javascript and for the first time using angular. Any help on this would be appreciated

Sinscary
  • 652
  • 12
  • 32
  • 2
    Possible dupe? http://stackoverflow.com/questions/25180332/how-can-i-listen-for-a-click-and-hold-in-angularjs EDIT : May not be a dupe, but it has the pieces you need. – mvc_help Jan 10 '17 at 10:43
  • I don't want to create an directive. i just want the time in seconds. – Sinscary Jan 10 '17 at 10:47
  • @Sinscary: Check my answer below, is that what you are expecting ? – Supradeep Jan 10 '17 at 11:50

1 Answers1

4

Instead of creating a separate directive, you can use the ngMouseUp and ngMouseDown directives to calculate the time difference as shown below.

Hope this is what you are expecting.

angular.module('myApp', [])

.controller('myCtrl', function ($scope){
  var timeStart, timeEnd;

  $scope.mouseDown = function () {
    timeStart = new Date();
  }


  $scope.mouseUp = function () {
   timeEnd = new Date();
   $scope.timeDiff = (timeEnd - timeStart)/1000;
  }  
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-mousedown='mouseDown()' ng-mouseup="mouseUp()">Click me and Hold</button>
  <p ng-if="timeDiff"> You have clicked the button for <b>{{timeDiff}}</b> seconds</p>
</div>
Supradeep
  • 3,246
  • 1
  • 14
  • 28