AngularJS表单输入焦点,数据不显示在模型中

时间:2013-06-26 15:05:19

标签: angularjs focus angularjs-directive setfocus autofocus

新手AngularJS,抱歉。

我希望某些表单输入可以根据特定条件设置焦点。 已找到答案 with this answer(focusMe)

问题是我的表单输入没有显示在模型中。

    <input type='text' name='school_name' ng-model='plan.school_name' focus-me="{{true}}"/>

这是一个 jsfiddle 来显示我的问题。

我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

您在指令定义对象上定义了scope属性。当您这样做时,您在整个元素的顶部创建一个隔离的范围,以便应用于该元素的所有其他指令(包括ngModel)也受其影响。

此问题已在其他地方得到解决(请参阅“form element ng-model change not observered in isolate scope directive watch”,“ngModel and component with isolated scope”和github issue 1924),但要克服这些问题非常麻烦。

在这种特殊情况下,我使用focus-me对象访问attrs属性(使用$ observe方法),而不是定义隔离范围:

var myApp = angular.module('myApp',[]).directive('focusMe', function($timeout) {
    return function(scope, element, attrs) {
        attrs.$observe('focusMe', function(value) {
            if ( value==="true" ) {
                $timeout(function(){
                    element[0].focus();
                },5);
            }
        });
    }
});

DEMO FIDDLE

相关问题