AngularJs:指令控制器中的document.body.onfocus

时间:2015-07-07 04:28:21

标签: javascript html angularjs

我试图在用户关闭或取消File Upload窗口

时捕获事件

<input type="file">

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

我正在使用javascript

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

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

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

来自@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!');
        });
    }

1 个答案:

答案 0 :(得分:3)

使用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!');
            });
        }
    };
}]);