当我按下删除键盘时,Angularjs DELETE <div>

时间:2017-03-14 13:01:29

标签: javascript angularjs angularjs-directive keyboard

我创建了一个新指令,用于在用户按下delt键盘时删除,但它不起作用。我使用了angularjs指令:ng-keypress

指令:keyboard.js

yemp.planner.app .directive('onKeyEnter', ['$parse', function($parse) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            element.bind('keydown keypress', function(event) {
                if (event.which === 46) {
                    var attrValue = $parse(attrs.onKeyEnter);
                    (typeof attrValue === 'function') ? attrValue(scope) : angular.noop();
                    event.deleteTimelineItem();
                    console.log("delete");
                }
            });
            scope.$on('$destroy', function() {
                element.unbind('keydown keypress')
            })
        }
    };
}]);
<div class="time-lime-item-details" onKeyEnter >
    <!-- when the user press delete this div should be deleted -->
</di>

我将脚本行添加到html文件中:

<script type="text/javascript" src="scripts/directives/keyboard.js"></script>

1 个答案:

答案 0 :(得分:0)

为了捕获键盘事件,应该关注一个元素。默认情况下,div无法聚焦,但您可以为其设置tabindex="1"属性,以便在鼠标单击或调用focus()方法时捕获焦点(基于您的方案)。

How can I give keyboard focus to a DIV and attach keyboard event handlers to it?

此外,在附加元素的指令时,请使用dashdelimited notation on-key-enter而不是onKeyEnter