AngularJS - 单击复选框时聚焦输入元素

kol*_*rie 15 angularjs

在单击复选框时,是否有一种更清晰的方式将焦点委托给元素.这是我入侵的脏版本:

HTML

<div ng-controller="MyCtrl">
    <input type="checkbox" ng-change="toggled()">
    <input id="name">
</div>
Run Code Online (Sandbox Code Playgroud)

JavaScript的

var myApp = angular.module('myApp',[]);

function MyCtrl($scope, $timeout) {
    $scope.value = "Something";
    $scope.toggled = function() {
        console.debug('toggled');
        $timeout(function() {
            $('#name').focus();
        }, 100);
    }
}
Run Code Online (Sandbox Code Playgroud)

JSFiddle:http://jsfiddle.net/U4jvE/8/

max*_*sam 17

这个怎么样 ?plunker

 $scope.$watch('isChecked', function(newV){
      newV && $('#name').focus();
    },true);
Run Code Online (Sandbox Code Playgroud)

@asgoth和@Mark Rajcok是对的.我们应该使用指令.我只是懒惰.

这是指令版本.plunker我认为将其作为指令的一个很好的理由是你可以重用这个东西.

所以在你的HTML中,你可以只为不同的集合分配不同的模态

<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);
      };    
});
Run Code Online (Sandbox Code Playgroud)


Mar*_*cok 7

另一个指令实现(不需要jQuery),并借用一些@maxisam的代码:

myApp.directive('focus', function() {
    return function(scope, element) {
       scope.$watch('focusCheckbox', 
         function (newValue) { 
            newValue && element[0].focus()
         })
    }      
});
Run Code Online (Sandbox Code Playgroud)

HTML:

<input type="checkbox" ng-model="focusCheckbox">
<input ng-model="name" focus>
Run Code Online (Sandbox Code Playgroud)

小提琴.

由于此指令不创建隔离范围(或子范围),因此该指令假定范围已focusCheckbox定义属性.


Vin*_*res 5

如果你想让它更有趣,并且支持任何要评估的表达式(不仅仅是变量),你可以这样做:

app.directive('autofocusWhen', function ($timeout) {
    return {
        link: function(scope, element, attrs) {
            scope.$watch(attrs.autofocusWhen, function(newValue){
                if ( newValue ) {
                    $timeout(function(){
                        element.focus();
                    });
                }
            });
        }
     };
});
Run Code Online (Sandbox Code Playgroud)

你的html可以更加分离,就像那样:

<input type="checkbox" ng-model="product.selected" />
{{product.description}}
<input type="text" autofocus-when="product.selected" />
Run Code Online (Sandbox Code Playgroud)