Angular指令ng-repeat input设置焦点为使用add按钮添加的新选项

Angular directive ng-repeat input set focus to new option added using add button

本文关键字:添加 按钮 新选项 选项 add input ng-repeat 指令 设置 焦点 Angular      更新时间:2023-09-26

我有一个html页面的问题和能力添加多个选项与能力添加或删除一个选项。

如何将焦点设置为使用add button/link添加的新添加的选项文本框

这是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'
        };
});

你可以创建一个autofocus指令,它会在一个元素第一次被创建时给它一个焦点:

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

然后在question.html中为输入添加autofocus属性:

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

http://plnkr.co/edit/xW17yIgEaKS0oX4wVj23?p =预览