AngularJS - 单击复选框时聚焦输入元素 [英] AngularJS - Focusing an input element when a checkbox is clicked
问题描述
是否有一种更简洁的方法可以在单击复选框时将焦点委托给元素.这是我破解的脏版本:
HTML
<input type="checkbox" ng-change="toggled()"><输入id="姓名">
JavaScript
var myApp = angular.module('myApp',[]);函数 MyCtrl($scope, $timeout) {$scope.value = "东西";$scope.toggled = function() {console.debug('切换');$超时(功能(){$('#name').focus();}, 100);}}
JSFiddle:http://jsfiddle.net/U4jvE/8/
这个怎么样?plunker
$scope.$watch('isChecked', function(newV){新V&&$('#name').focus();},真的);
@asgoth 和@Mark Rajcok 是正确的.我们应该使用指令.我只是懒.
这是指令版本.plunker 我认为把它作为指令的一个很好的理由是你可以重用这个东西.
因此在您的 html 中,您可以将不同的模态分配给不同的集合
<input xng-focus='isCheckedN'>指令('xngFocus',函数(){返回函数(范围,元素,属性){范围.$watch(attrs.xngFocus,功能(新值){新价值&&element.focus();},真的);};});
Is there a cleaner way of delegating focus to an element when a checkbox is clicked. Here's the dirty version I hacked:
HTML
<div ng-controller="MyCtrl">
<input type="checkbox" ng-change="toggled()">
<input id="name">
</div>
JavaScript
var myApp = angular.module('myApp',[]);
function MyCtrl($scope, $timeout) {
$scope.value = "Something";
$scope.toggled = function() {
console.debug('toggled');
$timeout(function() {
$('#name').focus();
}, 100);
}
}
JSFiddle: http://jsfiddle.net/U4jvE/8/
how about this one ? plunker
$scope.$watch('isChecked', function(newV){
newV && $('#name').focus();
},true);
@asgoth and @Mark Rajcok are correct. We should use directive. I was just lazy.
Here is the directive version. plunker I think one good reason to make it as directive is you can reuse this thing.
so in your html you can just assign different modals to different sets
<input type="checkbox" ng-model="isCheckedN">
<input xng-focus='isCheckedN'>
directive('xngFocus', function() {
return function(scope, element, attrs) {
scope.$watch(attrs.xngFocus,
function (newValue) {
newValue && element.focus();
},true);
};
});
这篇关于AngularJS - 单击复选框时聚焦输入元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!