使用仅使用angularjs和jqlite进入键,选项卡选项卡、angularjs、jqlite

2023-09-13 05:03:44 作者:你和氧气同起坐

我已经看过多线程和尝试了广阔的多种解决方案。坦率地说,我认为我失去我的脑海里。

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

我有一个NG重复与投入。所有这一切需要做的是,当用户presses进入,应该将焦点切换到下一个输入,基本上模拟Tab键的功能。

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.

在code(不完全):HTML:

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>

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

下面是一个链接到小提琴:小提琴

Here is a link to the fiddle: fiddle

推荐答案

好了,我想通了。是不是终究难。刚刚在全赶上了思维定势,而采用了棱角分明不认为jQuery的。

Ok, so I figured it out. Wasn't that difficult after all. Just got caught up in the whole "don't think jQuery while using Angular" mindset.

下面是我实现的指令:

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

下面是链接到工作小提琴:进入-作为标签

Here is the link to the working fiddle: enter-as-tab