AngularJS - ngRepeat.在 ng 重复重新渲染后,需要将焦点集中在相同的元素事件上

AngularJS - ngRepeat. Need to keep focus on the same element event after ng-repeat re rendering

本文关键字:集中 焦点 元素 事件 ng ngRepeat 新渲染 AngularJS      更新时间:2023-09-26

>我有一个包含三个输入的列表,用户可以通过按放置在它们左侧的红叉来删除每个输入。当用户删除一个输入时,下一个输入将聚焦并删除所选复选框。直到到目前为止一切顺利。删除元素后,ng-repeat循环迭代更新的模型,我失去了元素焦点。有什么办法可以防止这种情况吗?

非常感谢,

吉列尔莫

PD:包括指令代码以防万一。

directive('checkEmptyInput', function ($timeout,$q) {
    return {
        restrict: 'A',
        require: '?ngModel',
        link: function (scope, element, attrs, ngModel) {
            if(!ngModel) return; //do nothing if no ng-model
            var idx = scope.$index,
                array = [],
                fieldIsValid = false;

            element.on('keyup', function () {

                switch (attrs.checkEmptyInput) {
                    case "method":
                        array = scope.album.tracks;
                        fieldIsValid = scope.ngAlbumForm.track.$valid;
                    break;
                }
                if(array[idx].name && array[idx].name != "" && fieldIsValid) {
                    array[idx].active = true;
                } else {
                    array[idx].active = false;

                    if(scope.elementHasId(array[idx])){
                        scope.deleteKeyFromCombinationsCodes(array[idx].id);
                    }
                };
                if (array[idx].name == "") {
                    //Previous to delete focus the next element
                    $timeout(function () {
                        var nextElem = element.parent().next().find('input')[0];
                        if(nextElem !== undefined) {
                            if(!scope.$last) {
                                //Delete the element
                                console.log("Deleting from inside the directive...");
                                nextElem.focus();                                   
                                scope.$emit("deleteArrayElement", [idx]);
                            }
                        }
                    });
                }
            });
        }
    }
})

.HTML:

                    <div ng-repeat="track in album.tracks">
                        <input check-empty-input="track" type="text" ng-change="addInputText($index,$last,track.name,album.tracks;" ng-minlength="3" class="album_tracks" ng-model="track.name" ng-unique="track"/><button type="button"/>
                        <i class="remove-icon"></i>
                        </button>
                    </div>

普伦克:http://plnkr.co/edit/BRN9csBcxHp5QU96NKq9?p=info

啊,我看到的是扑通。 ng-repeat重用元素,并在初始链接期间选取索引。 如果您在keyup处理程序中设置idx,它将起作用。 (波兰兹罗提)

element.on('keyup', function () {
    idx = scope.$index;