2013-06-26 104 views
0

AngularJS的新手,抱歉。AngularJS表单输入焦点,数据不显示在模型中

我希望某些表单输入可以根据特定标准对其进行焦点设置。 发现已经有答案with this answer(focusMe)

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

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

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

我在做什么错在这里?

+0

存在一些问题,在正常的jsfiddle应用程序工作正常 –

+0

不,这是我在我的应用程序中完全相同的行为 –

回答

1

您在指令定义对象上定义了范围属性。当你这样做的时候,你在整个元素的顶部创建了一个独立的范围,以便应用于该元素的所有其他指令(包括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对象的(使用$观察法):

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

+0

真棒,谢谢 –

相关问题