我一直在尝试实施此处建议的内容和其他类似的解决方案 如何将焦点设置在输入字段上?
用不工作的自动对焦插入我的代码。
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';
}
});
没有一个解决方案对我有用。每当模式打开时,我都会以某种方式将焦点设置在文本框上,但随后我不再获得userName1
through的价值ng-model
。执行focusMe
指令后userName1
始终未定义。
编辑
打算试试这个 我可以使用隔离范围的 ng-model 吗?
因为它似乎ng-model
不适用于上述解决方案
同时,任何人都回答了我的问题 “如何在 twitter-bootstrap 模态中设置自动对焦到文本框并能够通过 ng-model 获取在该文本框中输入的值”,请分享。