AngularJS - 点击复选框时聚焦一个input元素 [英] AngularJS - Focusing an input element when a checkbox is clicked
本文介绍了AngularJS - 点击复选框时聚焦一个input元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有被点击复选框时委托焦点元素的更清洁的方式。这里的脏版我砍死:
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/
推荐答案
这个怎么样? plunker
$scope.$watch('isChecked', function(newV){
newV && $('#name').focus();
},true);
@asgoth和@马克Rajcok是正确的。我们应该用指令。我只是懒惰。
@asgoth and @Mark Rajcok are correct. We should use directive. I was just lazy.
下面是该指令的版本。 plunker 我认为一个好理由,使之作为指令是可以重用这个事情。
Here is the directive version. plunker I think one good reason to make it as directive is you can reuse this thing.
所以在你的HTML你可以分配不同的情态,以不同的套
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 - 点击复选框时聚焦一个input元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文