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

时间:2012-12-28 22:51:39

标签: angularjs

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

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/

4 个答案:

答案 0 :(得分:17)

这个怎么样? plunker

 $scope.$watch('isChecked', function(newV){
      newV && $('#name').focus();
    },true);

@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);
      };    
});

答案 1 :(得分:7)

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

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

HTML:

<input type="checkbox" ng-model="focusCheckbox">
<input ng-model="name" focus>

Fiddle

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

答案 2 :(得分:5)

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

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

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

<input type="checkbox" ng-model="product.selected" />
{{product.description}}
<input type="text" autofocus-when="product.selected" />

答案 3 :(得分:0)

更简洁的方法是使用指令来执行切换:

app.directive('toggle', function() {
   return {
      restrict: 'A',
      scope: {
         selector: '='
      },
      link: function(scope, element, attrs) {
          element.on('change', function() {
              $(scope.selector).focus();
              scope.$apply();
          });
      }
   }:
});

你的html会像:

<input type='checkbox' toggle selector='#name'>
相关问题