在单击复选框时,是否有一种更清晰的方式将焦点委托给元素.这是我入侵的脏版本:
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/
max*_*sam 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);
      };    
});
另一个指令实现(不需要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>
小提琴.
由于此指令不创建隔离范围(或子范围),因此该指令假定范围已focusCheckbox定义属性.
如果你想让它更有趣,并且支持任何要评估的表达式(不仅仅是变量),你可以这样做:
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" />
| 归档时间: | 
 | 
| 查看次数: | 29180 次 | 
| 最近记录: |