angular js - 使用ng-click聚焦文本框

时间:2015-02-10 10:26:36

标签: angularjs focus angularjs-scope angularjs-ng-click

我正在尝试构建一个Angular JS表单。我希望用户能够在单击按钮时将焦点设置在文本字段上。不知道为什么这不起作用?感谢

HTML:

<div ng-app="" ng-controller="personController">
  <p>Name: <input type="text" ng-model="name" id="question1" focus="{{focusThis}}"></p>
  <p ng-bind="name"></p>
  <input type="button" value="focus" ng-click="focus()">
</div>

Angular JS功能:

function personController($scope)
   {$scope.focus=function(){
    $scope.focusThis="true";
   };
};

3 个答案:

答案 0 :(得分:4)

一些通用解决方案($jQuery):

mod.directive('nsFocusId', ['$timeout', function($timeout) {
  return {
    restrict: 'A',
    link: function(scope, element, attrs, ctrl) {
      element.click(function() {
        $timeout(function () { $('#' + attrs.nsFocusId).focus(); }, 0);
      });
    }
  };
}]);

用法:

<label data-ns-focus-id="id-of-target-element">a</label>

此指令可用于任何元素,它将按您提供的id关注元素 我使用$timeout只是为了让它更灵活,以便将来升级(但可以用scope.$apply函数包装它;)

答案 1 :(得分:2)

https://docs.angularjs.org/api/ng/directive/ngFocus

ng-focus在元素聚焦时执行表达式,因此它实际上不会将元素设置为聚焦,而是响应聚焦。

How to set focus on input field?

检查此资源或谷歌搜索“如何设置一个关注元素”,它应该以正确的方式引导您。

答案 2 :(得分:-3)

我修改了你的代码,检查它。

<div ng-app="TestApp" ng-controller="personController">
  <p>Name: <input type="text" ng-model="name" id="question1" ></p>
  <p ng-bind="name"></p>
  <input type="button" value="focus" ng-click="focus()">
</div>


var app = angular.module('TestApp', []);

app.controller('personController', function ($scope, $http, $log) {

   $scope.focus = function () {
     $("#question1").focus();
    console.log($("#question1"));
   }
});