Problems with keystroke events in angular

I'm new to Angular, help would be greatly appreciated. I am creating an application that has different areas, let it be called pages (although this is really an application with 1 page), for which I naturally use different views, and I have a common layout with the body, styles and scripts, etc.

I had a problem when I want to listen to keyboard events only on one of the pages of the application, which should be interactive and the other administrative. I can associate keyboard events with inputs or a document or body. The input is not suitable, and my document and body are global, and I do not want to listen to every keystroke in my application.

What should I do to solve this problem in Angular?

My code is here: https://github.com/mgenev/geminiFc/blob/master/public/js/controllers/practice.js

I tricked jQuery and associated the event with the body in the controller for a specific page, but Angular did not react the way the event happened.

$('body').keydown(function(e) {
            $scope.changeIndex(e);
});

Then I read that I need to use $ scope. $ apply (); which I did at the bottom of the changeIndex function that the event fires.

It really worked, but when I call changeIndex through the click event, which is an alternative way to control my user interface

   <div class="practice-controls-bottom">
        <i ng-click="changeIndex('down');" class="icon-thumbs-down icon-4x thumbs-down"></i>
        <i ng-click="changeIndex('up');" class="icon-thumbs-up icon-4x thumbs-up pull-right"></i>
    </div>

Angular gives me an error:

Error: $apply already in progress
    at Error (<anonymous>)
    at g (http://localhost:3000/lib/angular/angular.min.js:85:37)
    at Object.e.$apply (http://localhost:3000/lib/angular/angular.min.js:89:129)
    at Object.$scope.changeIndex (http://localhost:3000/js/controllers/practice.js:173:20)

Looking forward to some tips. Thanks!

+4
source share
2 answers

:

$scope. $ keydown changeindex

$('body').keydown(function (e) {
    $scope.$apply(function () {
        $scope.changeIndex(e);
    })
});

, apply/digest $apply changeIndex ,

if(!$scope.$$phase){
    $scope.$apply()
}
+5

ng-keypress, ng-keyup, ng-keydown? , , .

Doc: http://docs.angularjs.org/api/ng.directive:ngKeypress

EDIT: tabindex="0", .

: http://plnkr.co/edit/whXgmQU1pKjuRqvokC2Z

HTML

<div ng-keypress="changeIndex($event)" tabindex="0">Something</div>

JS

app.controller('MyCtrl', [function($scope) {
    $scope.changeIndex = function($event) {
        // $event.keyCode...
    }
}]); 

Angular -UI http://angular-ui.imtqy.com/ui-utils/, .

<div ui-keypress="{13:'changeIndex($event)'}"></div>
+2

All Articles