Freya Freya - 2 months ago 15
AngularJS Question

Call scope function inside onkeydown event

I have the following html:

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


A value (true / false) is fetched from the database and passed to the ng-model. Depending on it, the checkbox is checked / uncheked. The function inside ng-blur triggers the update in the database and works:

$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
});
}
};


The issue is that I would have to use the checkbox from other devices that don't support the click event. From these devices I should use the equivalent of enter (keycode 13). So I added the onkeydown event to detect when the enter key is being pressed on the checkbox. Using an example from w3schools, I see it works (here is the example 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()">


Now I want to call the update function when the onkeydown event detects that the code 13 was pressed. Something like this:

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


However, calling update_show_value inside the keycode function does not work. Actually, adding update_show_value inside the keycode function causes everything else not to work (ex. the alert)

So for some reason I think that scope functions cannot be called inside javascript functions. If that is true, is there a workaround?

2ps 2ps
Answer

You can get the scope object outside of Angular by using:

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

You can define your own directive to handle keydown

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

Or just use ng-keydown instead: https://docs.angularjs.org/api/ng/directive/ngKeydown :

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