Angular ng-repeat:当顺序改变时,将焦点放在输入上



我使用ng-repeat来显示有序列表。我在列表中有一个输入,你可以在其中指定顺序。当你改变它时,有时它会保持焦点(当输入向下时),但当输入被排序时,我就会失去对输入的关注。我怎么解决这个问题?

示例:http://jsfiddle.net/Q3Xfe/

<div ng-app ng-controller="MyCtrl">
    <div ng-repeat='person in Persons | orderBy: "number" track by person.id'>
        <p>{{ person.name }} <input type='number' ng-model='person.number'></p>
    </div>
</div>

更通用的方法:

app.directive("keepFocus", ['$timeout', function ($timeout) {
    /*
    Intended use:
        <input keep-focus ng-model='someModel.value'></input>
    */
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function ($scope, $element, attrs, ngModel) {
            ngModel.$parsers.unshift(function (value) {
                $timeout(function () {
                    $element[0].focus();
                });
                return value;
            });
        }
    };
}])

然后:

<input keep-focus ng-model="person.number"/>

我认为这是由于当顺序改变时重新创建DOM元素的方式。我制定了一个指令来保持注意力。我不确定这是不是最好的方法,但它是有效的。

app.directive('setFocus', function($timeout, $rootScope) {
    return {
        restrict: 'A',
        scope: {
            personId: '@',
            index: '@',
            selectedPersonId: '@'
        },
        link: function($scope, $element, attrs) {
            $scope.$watch("index", function(currentValue, previousValue) {
                if($scope.personId == $scope.selectedPersonId)
                {
                    $timeout(function(){
                        $element[0].focus();
                    });
                }
            })
        }
    }
});

传入元素的personId、元素的索引和selectedPersonId(以具有焦点的为例)。它观察索引的变化,然后检查元素的personId是否等于selectedPersonId(如果等于则设置焦点)。

HTML是这样的:

<input class='filter' type='number' ng-model='person.number' ng-focus="selectPerson(person.id)" set-focus person-id="{{person.id}}" selected-person-id="{{selectedPersonId}}" index="{{$index}}">

似乎做一些看起来很简单的事情要做很多额外的事情。也许别人有更聪明的办法。

最新更新