Angular Js Textbox不关注按钮点击

时间:2016-09-01 10:44:07

标签: html angularjs

无法在按钮点击时关注文本框:

<html ng-app="CommonApp">
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-controller="HeadCtrl" ng-init='username=""'>
    <input id="UserName" type="text" class="login_boxdecor" ng-model="username" />
    <div class="login_btn_outer">
        <div class="login_btn_outer2" ng-click="cLgn();">
            <a class="btn">Login</a>
        </div>
    </div>
</body>
</html>
var myApp = angular.module('CommonApp', []);
    myApp.controller('HeadCtrl', function($scope){
        $scope.cLgn= function(){
            if($scope.username.trim().length==0)
            {
                //Here How to focus my textbox
            }
        };
    });

2 个答案:

答案 0 :(得分:1)

<html ng-app="CommonApp">
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-controller="HeadCtrl" ng-init='username=""'>
    <input id="UserName" type="text" class="login_boxdecor" ng-model="username" />
    <div class="login_btn_outer">
        <div class="login_btn_outer2" ng-click="cLgn();">
            <a class="btn">Login</a>
        </div>
    </div>
</body>
</html>
var myApp = angular.module('CommonApp', []);
    myApp.controller('HeadCtrl', function($scope){
        $scope.cLgn= function(){
            if($scope.username.trim().length==0)
            {
                document.getElementById("UserName").focus();
            }
        };
    });

答案 1 :(得分:0)

您可以使用angular.element选择输入框并调用focus()。尝试类似下面的内容::

 <html ng-app="CommonApp">
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-controller="HeadCtrl" ng-init='username=""'>
    <input id="UserName" type="text" class="login_boxdecor" ng-model="username"/>
    <div class="login_btn_outer">
        <div class="login_btn_outer2" ng-click="cLgn();">
            <a class="btn">Login</a>
        </div>
    </div>
</body>
</html>
var myApp = angular.module('CommonApp', []);
    myApp.controller('HeadCtrl', function($scope){
        $scope.focusText =false;
        $scope.cLgn= function(){
            if($scope.username.trim().length==0)
            {
                 angular.element("#UserName").focus();
            }
        };
    });