如何将焦点保持在Angular中的相同文本字段中

时间:2014-01-01 02:01:49

标签: javascript angularjs

我是Angular的新手,我正在使用Angular编写应用程序,用户可以使用它 输入几个要发送到服务器的代码。 用户将输入代码并按 Enter Tab 将其发送到服务器。 我需要专注于该领域,以便他可以输入下一个代码。 Enter 键工作正常,但当我按 Tab 时,它会失去焦点。

我的HTML代码是这样的:

<body ng-app="POT">
    <br/>
    <div ng-controller="RecordPotController" align="center">
        <div><b>{{hello}}</b>

        </div>
        <br/>
        <form ng-submit="do_record_pot()">
            <table width='400'>
                <tr>
                    <td>POT Code:</td>
                    <td>
                        <input id="myFocus" focus-on="focusMe" type="text" ng-model="keywords" ng-blur="do_record_pot()" placeholder="Enter POT code" />
                    </td>
                </tr>
            </table>
        </form>
        <br/>
        <hr/>
<pre ng-model="result">
result: {{result}}<br/>
message: {{msg}}<br/>
status: {{status}}<br/>
</pre>

    </div>
</body>

我的JS代码如下:

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

app.directive('focusOn', function () {
    return function (scope, elem, attr) {
        scope.$on('focusOn', function (e, name) {
            if (name === attr.focusOn) {
                elem[0].focus();
            }
        });
    };
});

app.factory('focus', function ($rootScope, $timeout) {
    return function (name) {
        $timeout(function () {
            $rootScope.$broadcast('focusOn', name);
        });
    }
});

app.controller("RecordPotController", function ($scope, focus) {
    focus('focusMe');
    $scope.hello = "Enter POT code and press Tab key";

    $scope.do_record_pot = function () {
        $scope.result = "POT recorded: " + $scope.keywords;
        $scope.msg = "now enter next code";
        $scope.keywords = "";
        $scope.status = 123;
    };

});

我创建了一个小提琴来展示这个例子 -

http://jsfiddle.net/patildg/LN4J8/67/

我应该如何将重点放在该领域?

2 个答案:

答案 0 :(得分:0)

app.directive('noTab', function() {
    return {
        restrict: "A",
        link: function($scope,$element) {
            $element.on("keydown keypress", function(event) {
                if(event.which === 9) { 
                  event.preventDefault();
                }

            });
        }
    }
});

http://jsfiddle.net/LN4J8/68/

答案 1 :(得分:0)

您是否考虑过使用ngKeydown?在这种情况下可能更合适。

HTML:

<input id="myFocus" type="text" ng-model="keywords" placeholder="Enter POT code" ng-keydown="keyDown($event)" />

JS:

app.controller("RecordPotController", function ($scope) {
    var do_record_pot = function () {
        $scope.result = "POT recorded: " + $scope.keywords;
        $scope.msg = "now enter next code";
        $scope.keywords = "";
        $scope.status = 123;
    };

    $scope.hello = "Enter POT code and press Tab key";

    $scope.keyDown = function (event) {
        if (event.keyCode === 9 || event.keyCode === 13) {
            do_record_pot();
            event.preventDefault();
        }
    };
});

http://jsfiddle.net/Gxh5U/1/