我一直在尝试实施此处建议的内容和其他类似的解决方案如何将焦点设置在输入字段上?
PLUNKER我的代码无法正常工作自动对焦。
HTML
<body ng-controller='userNameController'>
<button class="btn" id="enterUsernameBtn" href="#userNameModal" role="button" class="btn" data-toggle="modal" title="Enter Username"
ng-click="focusInput=true">Enter Username</button>
<!-- UserName Modal -->
<div id="userNameModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="userNameModalLabel"
aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="userNameModalLabel">Enter your username</h3>
</div>
<div class="modal-body">
<div class="input-append">
<input class="pull-left" id="userIdTextBox" type="text"
ng-model="userName1" ng-minlength="1" ng-trim="true" focus-me="focusInput"/>
</div>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="{{whatToDismiss}}" aria-hidden="true" ng-click="submitUserName()">Submit</button>
</div>
</div>
</body>
JavaScript
var app = angular.module('abcApp',[]);
app.directive('focusMe', function($timeout) {
return {
scope: { trigger: '@focusMe' },
link: function(scope, element) {
scope.$watch('trigger', function(value) {
if(value === "true") {
$timeout(function() {
element[0].focus();
});
}
});
}
};
});
app.controller('userNameController',function ($scope)
{
$scope.whatToDismiss=''; // workaround not to close the modal if it is an invalid input
$scope.focusInput=false;
$scope.submitUserName= function ()
{
if($scope.userName1===undefined || $scope.userName1==="")
{
alert("Invalid Input");
return;
}
alert("username entered"+$scope.userName1);
$scope.whatToDismiss='modal';
}
});
没有一个解决方案对我有用。每当模式打开时,我都会以某种方式将焦点设置在文本框上,但随后我no more得到的值userName1
通过ng-model
。实施后focusMe
指示userName1
始终是未定义的。
Edit
打算试试这个我可以在隔离范围内使用 ng-model 吗?
因为看起来ng-model
不适用于上述解决方案
与此同时,有人来回答我的问题“如何将自动焦点设置为 twitter-bootstrap 模式内的文本框,并能够通过 ng-model 获取在该文本框中输入的值”请分享。
我修改了你的笨蛋,http://plnkr.co/WKq83K,并创建了这个工作插件:http://plnkr.co/edit/fsBjsW?p=preview
变化如下:
Use focus-me
, not focusMe
:
<input class="pull-left" id="userIdTextBox" type="text" ng-model="userName1"
ng-minlength="1" ng-trim="true" focus-me="focusInput">
Set focusInput
to true
当对话框打开时:
<button class="btn" id="enterUsernameBtn" href="#userNameModal" role="button"
class="btn" data-toggle="modal" title="Enter Username"
ng-click="focusInput=true">Enter Username</button>
将其设置回false
当对话框提交时:
$scope.submitUserName= function() {
$scope.focusInput = false;
...
或取消:
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"
ng-click="focusInput=false">x</button>
$timeout
需要等待一段时间才能呈现模式。小于 480 的值似乎不起作用,所以我使用了更大的值,700:
$timeout(function() {
element.focus();
}, 700);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)