输入自动对焦属性 [英] Input autofocus attribute

查看:31
本文介绍了输入自动对焦属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码中有这样的地方:

I have places in my code where I have this:

<input data-ng-disabled="SOME_SCOPE_VARIABLE" />

我也希望能够像这样使用它:

I would like to be able to use it like this too:

<input data-ng-autofocus="SOME_SCOPE_VARIABLE" />

或者更好的是,模仿 ng-style 是如何完成的:

Or even better, mimicking how ng-style is done:

<input data-ng-attribute="{autofocus: SOME_SCOPE_VARIABLE}" />

当前版本的 AngularJS 中是否存在这种情况?我注意到在代码中有一个 BOOLEAN_ATTR 可以获取 AngularJS 支持的所有属性.我不想修改它,因为害怕更改版本和忘记更新.

Does this exist in the current version of AngularJS? I noticed in the code there's a BOOLEAN_ATTR which gets all the attr's that AngularJS supports. I don't want to modify that in fear of changing versions and forgetting to update.

推荐答案

更新:AngularJS 现在有一个 ngFocus 指令,用于评估表达式 on 焦点,但为了完整起见,我在这里提到它.

Update: AngularJS now has an ngFocus directive that evaluates an expression on focus, but I mention it here for the sake of completeness.

当前版本的 AngularJS 没有 focus 指令,但它在路线图中.巧合的是,昨天我们在邮件列表上谈论这个,而我想出了这个:

The current version of AngularJS doesn't have a focus directive, but it's in the roadmap. Coincidentally, we were talking about this on the mailing list yesterday, and I came up with this:

angular.module('ng').directive('ngFocus', function($timeout) {
    return {
        link: function ( scope, element, attrs ) {
            scope.$watch( attrs.ngFocus, function ( val ) {
                if ( angular.isDefined( val ) && val ) {
                    $timeout( function () { element[0].focus(); } );
                }
            }, true);

            element.bind('blur', function () {
                if ( angular.isDefined( attrs.ngFocusLost ) ) {
                    scope.$apply( attrs.ngFocusLost );

                }
            });
        }
    };
});

根据您的要求使用范围变量:

Which works off a scope variable as you requested:

<input type="text" ng-focus="isFocused" ng-focus-lost="loseFocus()">

这是一个小提琴:http://jsfiddle.net/ANfJZ/39/

这篇关于输入自动对焦属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆