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



我有以下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();
};

从$scope中删除()。update_show_value
试试下面的代码:

<script>
 var app=angular.module("myApp", []);
  app.controller("myCtrl", function($scope) {
    $scope.update_show_value = function() {
        alert(1);
    };
  });
</script>

最新更新