Jquery 关注ng repeat生成的输入
html代码Jquery 关注ng repeat生成的输入,jquery,angularjs,Jquery,Angularjs,html代码 <div class="row" ng-repeat="form in data.forms track by $index"> <form name="myForm"> <input id="search_{{$index}}" type="text" name="location" ng-model="form.query" ng-keyup="keyUp($index)" >
<div class="row" ng-repeat="form in data.forms track by $index">
<form name="myForm">
<input id="search_{{$index}}" type="text" name="location" ng-model="form.query" ng-keyup="keyUp($index)" >
</form>
</div>
上面的代码可以工作,但需要额外的setTimeout。是否有更好的方法等待表单生成,然后执行focus()?Angular的第一条规则:不要在指令范围之外接触DOM
ngRepeat
中的第一个输入元素可以通过自定义指令进行聚焦,该指令将使用以下自动提供的$First
范围变量:
app.directive('focusedOn'[
“$timeout”
,函数($timeout){
返回函数($scope、$element、$attrs){
函数焦点(){
$timeout(函数(){
$element.focus();
}, 20);
}
if(($attrs.focusedOn).isEmpty()){
返回焦点();
}
$scope.$watch($attrs.focusedOn,函数(newVal){
if(newVal){
焦点();
}
});
};
}
]
);
注意:如果没有$timeout,它可能会工作,也可能不会工作
$scope.data = {
forms: []
};
jQuery(document).ready(function() {
setTimeout(function() {
jQuery('#search_0').focus();
}, 500);
});