检测 window 以 angular 方式聚焦?

Detecting window focus the angular way?

有没有好的angular方法来检测window焦点?我正在使用 html5 通知,我只想在 window 失焦时触发。

谢谢!

您可以编写附加到 body 元素的指令,在其中您可以使用 $window.onfocus 事件来使用事件或服务通知您的 angular 应用程序,您可以做同样的事情从服务内部来看,这完全取决于您的架构

Edit @CristiBerceanu 是对的 - 您应该使用内置的 ng-focus 指令。但是,请将此答案作为您要绑定的任何缺失事件的指南。

您必须创建指令:

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);
            });
        }
    }
});

注意事件是如何通过 jquery 在指令中绑定的,而不是直接在控制器中。此外,请注意绑定表达式是使用 & 前缀(可计算表达式绑定)而不是像 @(文本绑定)或 =(范围 属性)这样的常规前缀来绑定的参考,双向,绑定)。

有一个内置的 angular 指令 ngFocus here 如果您将它附加到主体上,也许它会有所帮助

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

编辑:对于 window 焦点,有 $window 包装器,您可以执行以下操作:

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

在 Cristi Berceanu 的回答中,他建议将一个函数分配给 $window.onfocus,这确实有效。但是,这有一个问题......一次只能将一个函数分配给 $window.focus 。因此,通过将函数分配给 $window.onfocus,您可能会不小心覆盖以前的函数,并且您的函数以后也很容易被覆盖。

这是一个不同的解决方案,允许多个函数 运行 与 window 的焦点或模糊事件:

var onFocus = function () {
    // do something
};

var onBlur = function () {
    // do something else
};

var win = angular.element($window);

win.on("focus", onFocus);
win.on("blur", onBlur);

这将允许您为 $window 对象的焦点和模糊事件分配多个函数。

如果您在控制器中添加了函数,并希望在控制器被销毁时删除这些函数,您可以这样做:

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

受此 post 启发的解决方案:https://www.bennadel.com/blog/2934-handling-window-blur-and-focus-events-in-angularjs.htm