javascript - 在 onkeydown 事件中调用作用域函数

标签 javascript jquery html angularjs

我有以下 html:

<input type="checkbox" ng-model="user.show_value" ng-blur="update_show_value()"> 

从数据库中获取值(true/false)并将其传递给 ng-model。根据它,该复选框被选中/取消选中。 ng-blur 内部的函数触发数据库中的更新并起作用:

$scope.update_show_value() = function() {   
            if ($scope.user.show_value != undefined) {
                $scope.loading = true;
                //IF VALUE IS VALID, CALL THE UPDATEPIN FUNCTIONn
                User.updatevalue($scope.user)
                    //IF SUCCESSFUL, GET VALUE
                    .success(function(data) {
                        $scope.loading = false;
                        $scope.formData = {}; //CLEAR FORM SO THAT USER CAN ENTER NEW DATA
                        $scope.user.show_value = {type : $scope.user[0].show_value}; //PASS VALUE IN OUR SCOPE
                    });
            }
        };  

问题是我必须使用不支持点击事件的其他设备上的复选框。在这些设备中,我应该使用相当于 Enter 的键(键码 13)。因此,我添加了 onkeydown 事件来检测何时在复选框上按下回车键。使用 w3schools 的示例,我发现它有效(这里是示例 http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_event_key_keycode3 )

 <input type="checkbox" ng-model="user.show_value" onkeydown="keyCode(event)" ng-blur="update_show_value()"> 

现在我想在 onkeydown 事件检测到代码 13 被按下时调用更新函数。像这样的事情:

<script>
function keyCode(event) {
    var x = event.keyCode;
    if (x == 13) {
        alert ("You pressed the Escape key!");
        update_show_value();
    }
}
</script>

但是,在 keycode 函数内调用 update_show_value 不起作用。实际上,在 keycode 函数中添加 update_show_value 会导致其他所有功能都不起作用(例如警报)

因此,出于某种原因,我认为作用域函数不能在 javascript 函数内部调用。如果这是真的,有解决方法吗?

最佳答案

您可以使用以下方法在 Angular 之外获取作用域对象:

angular.element(event.target).scope(); // and then call whatever functions you want to on that scope object

您可以定义自己的指令来处理 keydown

angular.directive('myKeydown', [ function () {
    return {
        link: function(scope, elem, attrs) {
            element.bind('keydown', function() {
                scope.update_show_value();
            });
        }
    };
}]);

或者只是使用 ng-keydown 代替:https://docs.angularjs.org/api/ng/directive/ngKeydown :

$scope.keyCode = function($event) {
    . . . 
    $scope.update_show_value();
};

关于javascript - 在 onkeydown 事件中调用作用域函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39787372/

相关文章:

html - 图片下方的文字位于其他图片的顶部?

javascript - 在 HTML 5 的 Canvas 中制作数据图

javascript - 如何获得可用的字体粗细?

javascript - 聚合所选 div 的值

jQuery 可排序交换元素而不是插入

html - CSS段落中的重复颜色模式

javascript - 如何在 javascript 实时模板中自动建议类/函数名称?

javascript - 使用Javascript获取移动设备的实际高度

jquery - 另一个 html 页面中的事件在 Jquery Mobile 1.4 中不起作用

flash - 在 Internet Explorer 中通过 Flash 影片进行 DIVS