角度为

时间:2016-05-26 11:20:42

标签: jquery html angularjs

我在表中有一个表单,它动态添加带有[name field]输入元素的记录,选择类型[int,string,boolean]和一个用于创建具有相同字段的新记录的按钮,默认情况下应用焦点到ng-repeat中发生的新创建的行的按钮元素。我希望将焦点应用于名称输入字段,我在addNewParam函数中尝试了类似的内容来应用焦点:element($event.currentTarget).parent().parent().find('[name="new-input-param"] input')[0].focus();。有人可以建议我这样做的更好方法。这是表格的dom结构

<table class="table property-value">
<tbody>
    <tr>
        <th class="ng-binding">Name</th>
        <th class="ng-binding">Type</th>
        <th>&nbsp;</th>
    </tr>
    <!-- ngRepeat: param in pageParams track by $index --><tr ng-repeat="param in pageParams track by $index" class="ng-scope">
        <td name="input-param-name">
            <input class="form-control app-textbox app-widget-wrapper ng-pristine ng-untouched ng-valid ng-not-empty" name="input-param-name-name" type="text" placeholder="parameter name" ng-model-options="{updateOn: 'blur'}" ng-model="param.name" ng-change="onPageParamsUpdate()">
        </td>
        <td>
            <select name="input-param-type-name" class="form-control app-select ng-pristine ng-untouched ng-valid ng-not-empty" ng-model="param.type" ng-options="val for val in pageParamTypes.split(',')" ng-change="onPageParamsUpdate()"><option label="string" value="string:string" selected="selected">string</option><option label="integer" value="string:integer">integer</option><option label="boolean" value="string:boolean">boolean</option><option label="date" value="string:date">date</option></select>
        </td>
        <td>
            <button name="webservice-remove-param" class="app-button" ng-click="addNewParam($event, newParam)">
                <i class="glyphicon16 glyphicon glyphicon-plus"></i>
            </button>
        </td>
    </tr><!-- end ngRepeat: param in pageParams track by $index -->
</tbody>
</table>

这是addNewParam函数:

function addNewParam($event, newParam) {
if (!newParam.name) {
   wmToaster.show('error', $rs.locale.MESSAGE_ERROR_TITLE,    Utils.replace($rs.locale.MESSAGE_WARN_NAME_EMPTY_DESC, ['Param']));
} else {
Toaster.hide();
$s.pageParams.push(newParam);
$s.newParam = {'name': '', 'type': 'string'};
$s.onPageParamsUpdate();
element($event.currentTarget).parent().parent().find('[name="wm-new-input-param"] input')[0].focus();
}

}

1 个答案:

答案 0 :(得分:0)

自动对焦它可以完成这项任务。只需将此自定义指令添加到您的应用中。

app.directive('autoFocus', function($timeout) {
    return {
        restrict: 'AC',
        link: function(_scope, _element) {
            $timeout(function(){
                _element[0].focus();
            }, 0);
        }
    };
});

用法是:

<input name="theInput" auto-focus>

有关更多选项,请参阅How to set focus on input field?