user3386442
user3386442

Reputation: 1

Angular - identify scope or controller

I am new to Angular (1 week) and would like to know how to identify a particular controller within a view. I have a page with 5 separate stopwatches running that currently accept no keystrokes. Each of these stopwatches uses exactly the same controller, but in their own and are happy enough to run separately as I wanted. I would like to be able to use keystrokes to activate only one of these controllers eg if I hit A it would simulate pressing the "lap" button on the A stopwatch. But as each controller is the same name, I cannot determine how to send this keystroke to the correct stopwatch. I may be using Angular incorrectly so any advice would be appreciated. TIA. Jeremy

Upvotes: 0

Views: 694

Answers (2)

JeffryHouser
JeffryHouser

Reputation: 39408

Normally; a view wouldn't try to access a controller directly. You can associate a view element with a controller using the ng-controller tag, like this:

<div ng-controller="myController"></div>

It sounds like your "stopwatch" really is five separate instances of the same component; in which case I suggest you consider building a directive. A directive is like the Angular version of a component which can include display code and JavaScript code. The directive can have a controller defined and when you use the directive in your page there will be five independent instances of it; so the pressing the lap button in one should not affect the others.

Upvotes: 1

Chandermani
Chandermani

Reputation: 42669

Since your keyboard input is not linked to a focused element, you would have to bind to body keydown keypress events. For this create a directive like

app.directive('keyCapture', function () {
    return function (scope, element, attrs) {
        $('body').bind("keydown", function (event) {
            if(event.which === attrs.filter[0]) {
                scope.$apply(function (){
                    scope.callMethod();
                });
                event.preventDefault();
            }
        });
    };
});

You can use this directive now with

<div id='timer' key-capture="" filter="a"></div>
<div id='timer' key-capture="" filter="e"></div>

The controller should have the method callMethod which this directive would call correctly.

If you can use isolated scope, you can pass this method as part of scope object using &

Upvotes: 0

Related Questions