[英]Enable and set focus to text input field with checkbox in Angular JS
I have a Bootstrap 3 prepended text field with a checkbox. 我有一个带有复选框的Bootstrap 3前置文本字段。 I want the field to be disabled until the checkbox is true, and then I want to not only enable it but set focus to it
我希望禁用该字段,直到复选框为true,然后不仅要启用它,还要将焦点设置为该字段
I used the following code and the enable/disable works great, but not sure how to set the focus... 我使用以下代码,启用/禁用效果很好,但不确定如何设置焦点...
I will likely write a directive, but I was wondering if there was some very simple way to do it as there was for the disable/enable 我可能会写一条指令,但是我想知道是否有一些非常简单的方法来实现它,例如禁用/启用
<div class="input-group">
<span class="input-group-addon">
<input type="checkbox" name="cbprepend" ng-model="cbprepend">
</span>
<input type="text" id="cbprependfield" class="form-control" ng-disabled="!cbprepend">
</div>
Your approach using a directive is good, but lacks some "angularity". 使用指令的方法很好,但是缺乏“角度”。
Here is another possible solution. 这是另一种可能的解决方案。 First, create the directive:
首先,创建指令:
.directive('checkableInput', function() {
return {
restrict: 'E',
templateUrl: 'your/template/dir/checkable-input.html',
scope: {
id: "@",
model: "="
},
link: function (scope, element, attrs) {
var input = element.find('#' + scope.id);
scope.toggleFocus = function() {
if(scope.model) {
input.focus();
} else {
input.blur();
}
}
}
};
});
The template specified in templateUrl
looks like this: templateUrl中指定的
templateUrl
如下所示:
<div class="input-group">
<span class="input-group-addon" >
<input type="checkbox" ng-model="model" ng-change="toggleFocus()">
</span>
<input type="text" ng-id="id" class="form-control" ng-enabled="model">
</div>
This is how you use it: 这是您的用法:
<checkable-input id="cbprependfield" model="cbprepend" />
OK, I did use a Directive, not sure if this is the cleanest way, please give me some criticism... 好的,我确实使用了指令,不确定这是否是最干净的方法,请给我一些批评...
.directive('pcb', function() {
return {
restrict: 'A',
link: function postLink(scope, element, attrs) {
element.on({
change: function(e) {
if (element.is(':checked')) {
element.closest('.input-group').find('.focus-target').removeAttr('disabled')
element.closest('.input-group').find('.focus-target').focus();
} else {
element.closest('.input-group').find('.focus-target').attr('disabled', 'disabled');
element.closest('.input-group').find('.focus-target').blur();
}
}
});
}
};
});
with the html 与HTML
<div class="input-group">
<span class="input-group-addon" >
<input type="checkbox" pcb ng-model="cbprepend">
</span>
<input type="text" id="cbprependfield" class="form-control focus-target" disabled>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.