在Angularjs中的字段之间切换焦点

时间:2017-06-14 09:23:56

标签: javascript angularjs focus

如果用户按回车,我需要在字段之间切换焦点。如果两个字段(login& pwd)都不为空,则调用$ scope.submit。问题是如何在这两个领域之间切换焦点?我可以使用document.getElementByid来做,但是如果没有id attr?如何使用ng-model来设置angularjs html标签以设置焦点?

JS:

app.controller('loginCtrl', function($scope, $location, $rootScope,$http){
$scope.username = '';
$scope.password = '';
$scope.enter=function(){
    if ($scope.username!="" && ($scope.password=="" || $scope.password==undefined)) document.getElementById("password").focus();
    else if($scope.password!="" && ($scope.username=="" || $scope.username==undefined)) document.getElementById("username").focus();
    else if($scope.password!="" && $scope.username!="") $scope.submit();
};
$scope.submit=function(){
    var data={};
    data.login=$scope.username;
    data.pwd=$scope.password;
    $http.post("authorization.php", data).then(function success (response) {
        console.log(response);
        if (response.data['loggin'] === true) {
            $rootScope.loggedIn = true;
            $location.path('/dashboard');
            $rootScope.name = response.data['name'];
        }
        else {
            $scope.username = '';
            $scope.password = '';
        }
    },function error (response){
        console.log(response);
    }
    );

}
});

HTML:

<div ng-controller="loginCtrl"  class="login">
    <form action="/" id="myLogin" method="post">
        <input type="text" name="username" id="username" ng-model="username" placeholder="Username" required="required" class="input-txt" ng-keyup="$event.keyCode == 13 ? enter() : null"><br>
        <input type="password" name="password" id="password" ng-model="password" placeholder="Password" required="required" class="input-txt" ng-keyup="$event.keyCode == 13 ? enter() : null"><br>
        <br>
        <button type="button" ng-click="submit()"  class="btn btn--right">Login</button>
    </form>
</div>

1 个答案:

答案 0 :(得分:3)

我希望这会帮助你。谢谢。

<强> HTML

<input type="text" name="username" id="username" ng-model="username" placeholder="Username" required="required" class="input-txt" ng-keyup="$event.keyCode == 13 ? enter() : null" focus-me="setFocusValueName"><br>
<input type="password" name="password" id="password" ng-model="password" placeholder="Password" required="required" class="input-txt" ng-keyup="$event.keyCode == 13 ? enter() : null" focus-me="setFocusValuePwd"><br>  

指令

  directive('focusMe', function () {
      return {
        link: function (scope, element, attrs) {
          scope.$watch(attrs.focusMe, function (value) {
            if (value === true) {
              console.log('value=', value);
              element[0].focus();
              scope[attrs.focusMe] = false;
            }
          });
        }
      };
    });

<强>控制器

在控制器中为$ scope.setFocusValueName&amp;设置TRUE / FALSE; $ scope.setFocusValuePwd根据您的要求。

$ scope.setFocusValueName = true / false; $ scope.setFocusValuePwd = true / false;