Does window detection focus angular path?

Is there a good angular way to detect window focus? I use html5 notifications, and I would only like to run if the window is out of focus.

Thanks!

+6
source share
4 answers

There is a built-in angular ngFocus directive here , maybe this will help if you attach it to the body

 <window, input, select, textarea, a ng-focus=""> ... </window, input, select, textarea, a> 

Edit: there is a $window wrapper for the focus of the $window , and you can do something like:

  $window.onfocus = function(){ console.log("focused"); } 
+3
source

Edit @CristiBerceanu - you should use the ng-focus built-in directive. However, take this answer as a guideline for any missing event that you want to associate.

You must create a directive:

 angular .module('MyModule', []) .directive('onFocus', function(){ return { restrict: 'A', scope: { 'focus': '&onFocus' }, link: function($scope, $element, $attributes) { var focus = function(event) { $scope.focus({'$event': event}); }; $element.on("focus", focus); $scope.$on('$destroy', function(){ $element.off('focus', onClick); }); } } }); 

Notice how the event is associated with the jquery and NOT directives directly in the controller. Also, note that the associated expression is bound using the & prefix (test expression) instead of the usual prefixes, such as @ (text binding) or = (property property link, bidirectional, binding).

+3
source

you can write a directive to attach to the body element and inside it you can use the $ window.onfocus event to notify your angular application with events or a service, the same thing that you can do from inside the service, it all depends on your architecture

+1
source

In response to Christie Bercchan, he suggests assigning the function $ window.onfocus, which works. However, there is a problem with this ... only one function can be assigned to $ window.focus at a time. Thus, by assigning the function $ window.onfocus, you can accidentally overwrite the previous function, and your function will also be vulnerable to being overwritten later.

Here is another solution that allows you to run several functions with window focus or blur events:

 var onFocus = function () { // do something }; var onBlur = function () { // do something else }; var win = angular.element($window); win.on("focus", onFocus); win.on("blur", onBlur); 

This will allow you to assign several functions to the focus and blur events for the $ window object.

If you added functions inside the controller and want to remove these functions when the controller is destroyed, you can do something like this:

 $scope.$on("$destroy", function handler() { win.off("focus", onFocus); win.off("blur", onBlur); $interval.cancel(interval); }); 

Solution inspired by this post: https://www.bennadel.com/blog/2934-handling-window-blur-and-focus-events-in-angularjs.htm

+1
source

Source: https://habr.com/ru/post/980552/


All Articles