Using the enter key as tab using only angularjs and jqlite

avn*_*avn 6 angularjs jqlite

I have looked at multiple threads and tried a vast variety of solutions. Quite frankly I think I am losing my mind.

I have an ng-repeat with inputs. All that needs to happen is that when the user presses enter, it should shift focus to the next input, basically simulating the tab key functionality.

The code (incomplete): HTML:

<body ng-app="ap" ng-controller="con"> 
<table>
    <tr>
        <th>Name</th>
        <th>Age</th>
    </tr>
    <tr ng-repeat='person in persons'>
        <td>
            <input type='text'
                name="personName"
                ng-model="person.name" 
            />
        </td>
        <td>
            <input type='number'
                name="personName"
                ng-model="person.age" 
                enter-as-tab
            />
        </td>
    </tr>
</table>
Run Code Online (Sandbox Code Playgroud)

JS:

    var app = angular.module("ap", []);

app.controller("con", function ($scope) {

    $scope.persons = [
        { name: 'Susan', age: 1 }, 
        { name: 'Peter', age: 1 },
        { name: 'Jack', age: 2 }
    ];
});

app.directive('enterAsTab', function () {
    return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if(event.which === 13) {
                event.preventDefault();
                // Go to next age input                        
            }
        });
    };
});
Run Code Online (Sandbox Code Playgroud)

Here is a link to the fiddle: fiddle

avn*_*avn 10

好的,所以我明白了.毕竟不是那么困难.刚刚陷入了整体"在使用Angular时不要想jQuery"的心态.

这是我实施的指令:

app.directive('enterAsTab', function () {
    return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if(event.which === 13) {
                event.preventDefault();
                var elementToFocus = element.next('tr').find('input')[1];
                if(angular.isDefined(elementToFocus))
                    elementToFocus.focus();
            }
        });
    };
});
Run Code Online (Sandbox Code Playgroud)

以下是工作小提琴的链接:enter-as-tab