【问题标题】:AngularJs: document.body.onfocus inside directive controllerAngularJs:指令控制器内的document.body.onfocus
【发布时间】:2015-09-24 10:05:33
【问题描述】:

我试图在用户关闭或取消File Upload 窗口时捕获事件

<input type="file">

由于文件上传的关闭事件没有内置监听器,我试图通过document.body.focus 事件捕获它,类似于suggested here 的事件

我正在使用 javascript 运行它

document.body.onfocus = function() { console.log("hit me") }

现在我需要在指令中的 Angular 中实现它,以便我可以使用控制器中的对象将逻辑放入 focus 事件中。

如何在角度控制器内部访问document.bodyonfocus 事件?

来自@Phil 的建议(使用链接)

 ... this is a directive with controller
angular.directive("addPost", addPost);

addPost.$inject = ["$document", "$log"];

function addPost($document, $log) {

    return {
        ...
        link: link,
        ...
    };

    function link() {
        $document.find('body').on('focus', function (e) {
            $log.debug('HIT ME!');
        });
    }

【问题讨论】:

  • 尝试使用ng-focus
  • @AlbertoI.N.J.在我的应用程序中,<body> 元素在角度范围之外,我的意思是它在 MVC 视图上。如何将 ng-focus 附加到它上面?
  • 你可以试试$document.find('body').on('focus', function(e) { ... })
  • @LincAbela 这很奇怪,它肯定在我的应用程序中。你能显示你的代码吗?你也可以试试angular.element($document[0].body).on(...
  • 从头开始,document.find('body') 返回什么?我的猜测是控制器在指令附加到 DOM 之前被实例化。按照上面的建议使用链接功能。

标签: javascript html angularjs


【解决方案1】:

使用link/postLink函数来执行DOM操作。例如

.directive('addPost', ['$document', '$log', function($document, $log) {
    return {
        // snip
        require: 'addPost',
        link: function postLink(scope, element, attr, addPostCtrl) {
            // scope is shared with the controller
            // you can also access properties on the controller itself
            // via addPostCtrl
            $document.find('body').on('focusin', function(e) {
                $log.debug('HIT ME!');
            });
        }
    };
}]);

【讨论】:

  • 试过了。不知何故 - 焦点事件没有被击中。
  • @LincAbela 是否真的发生了任何 focus 事件?
  • 这是我的用例,我有一个 File Upload,我希望当我关闭 file upload window 时,它应该会点击 document.body.focus - 我通过 javascript 对其进行了测试,它确实点击了焦点事件。只是试图以角度实现它。这有意义吗?
  • @LincAbela 我认为“焦点”事件不会传播到身体。见stackoverflow.com/questions/9577971/…
  • 嗯。但是我在 javascript a<script> document.body.onfocus = function() { console.log("Hit ME"); } 中尝试过,但是当我关闭文件上传窗口时它会触发焦点事件。
猜你喜欢
  • 1970-01-01
  • 2014-04-07
  • 2013-03-15
  • 1970-01-01
  • 1970-01-01
  • 2015-07-29
  • 2014-01-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多