简体   繁体   中英

Mouse click/keyboard press event in AnguarJS

function getNumberOfStores() {
    $http.get("api/Stores/getAll").then(function(response) {
        $scope.data = response.data;
        var time = new Date();
        window.localStorage.setItem("loadedTime", time);
  });
}

I have a function to call the API to get the number of stores and the last loaded time is stored in local storage. After detecting mouse/keyboard clicks anywhere on the website, if the current time - last loaded time is > 5 days, I need to refresh the page. How can I check that the mouse is clicked or the keyboard is pressed in any of the controllers?

You could put ng-click and ng-keydown attributes on the body tag and then record those events however you like.

<body ng-click=‘clickEvent()’ ng-keydown=‘typeEvent($event)’</body>

Then you could the do something with those events in your controller.

$scope.clickEvent = function(){
    // do work
};

$scope.typeEvent = function(event){
    // do work
};

Edit: a better approach would be to use the $window service and bind the click and keydown events. Be sure to inject the $window service into your controller first.

$window.addEventListener('click', function(){
    // record click event 
});

$window.addEventListener('keydown', function(){
    // record keydown event
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM