javascript - Angular 指令 ng-repeat 输入将焦点设置为使用添加按钮添加的新选项

标签 javascript jquery html angularjs autofocus

我有一个 html 页面,其中包含问题和添加多个选项的能力以及添加或删除选项的能力。

如何将焦点设置到使用添加按钮/链接添加的新添加的选项文本框

这是 Plnkr 的链接

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.question = { question: 'what is your name',
     options: [{option:'Red', code: '1'}, {option:'Blue', code: '2'},
     {option:'Green', code: '3'},{option:'Black', code: '4'}]};
});

app.directive('myDirective', function(){
    return {
        link: function(scope, element, attrs, ctrls) {

                function Option() {
                    this.option = '';
                    this.code = '';
                }

                scope.addOption = function(index) {
                    var existingOption = scope.question.options;
                    if (existingOption && existingOption.length) {
                        var newOption = new Option(index + 1);
                        scope.question.options.splice(index + 1, 0, newOption);
                    }
                }

                scope.removeOption = function (index) {
                    if (index > -1) {
                        scope.question.options.splice(index, 1);
                    }
                }
            },
            restrict: 'AE',
            scope: {
                question: "="
            },
            templateUrl: 'question.html'
        };
});

最佳答案

您可以创建一个自动对焦指令,该指令将在元素首次创建时给予焦点:

.directive('autofocus', function($timeout) {
    return {
        link: function(scope, element, attrs) {
            $timeout(function() {
                element.focus();
            });
        }
    }
});

然后在question.html中给input加上autofocus属性:

<input type="text" autofocus class="form-control... />

http://plnkr.co/edit/xW17yIgEaKS0oX4wVj23?p=preview

关于javascript - Angular 指令 ng-repeat 输入将焦点设置为使用添加按钮添加的新选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39259167/

相关文章:

javascript - 使用某些过滤器 MongoDB 检索 n 个随机文档

javascript - 插入数组后 Angular 清除对象

javascript - 父单元格的输出id

javascript - 为什么在滚动元素中使用 offset().top 和 scrollTop() 时我的尺寸没有按预期返回?

javascript - 当点击 iframe 外部的按钮时,是否可以在 iframe 中写入内容?

javascript - 展开折叠树

javascript - 如果单击外部 div 则显示警报

javascript - eclipse:如何在现有 Android 项目上启用 JavaScript 验证

html - 如何设置div的宽度以适合内容?

javascript - JQuery 选项卡式内容 - SEO 友好的 URL