我正在尝试构建一个 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";
};
};
最佳答案
一些通用的解决方案怎么样($
是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
函数包装它);
关于angularjs - Angular JS - 使用 ng-click 聚焦于文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28429319/