programing

OrderBy 뒤에 Angularjs의 $index가 잘못됨

minimums 2023. 3. 4. 14:26
반응형

OrderBy 뒤에 Angularjs의 $index가 잘못됨

Angular.js는 처음이라 배열 정렬과 데이터 정렬에 문제가 있습니다.

아이템 리스트가 있으므로, 「Store.storeName」으로 정렬해 주세요.하지만 데이터를 정렬한 후 삭제 기능이 작동하지 않습니다.정렬 후 $index가 잘못되어 잘못된 데이터가 삭제되었기 때문이라고 생각합니다.

어떻게 하면 해결할 수 있을까요?뷰가 아닌 스코프에서 데이터를 정렬하시겠습니까?어떻게 하는 거야?

다음은 관련 코드입니다.

보기:

<tr ng-repeat="item in items | orderBy:'Store.storeName'">
                <td><input class="toggle" type="checkbox" ng-model="item.Completed"></td>
                <td>{{item.Name}}</td>
                <td>{{item.Quantity}} Stk.</td>
                <td>{{item.Price || 0 | number:2}} €</td>                
                <td>{{item.Quantity*item.Price|| 0 | number:2}} €</td>
                <td>{{item.Store.storeName}}</td> 
                <td><a><img src="img/delete.png" ng-click="removeItem($index)">{{$index}}</a></td>
            </tr>

컨트롤러에는 특정 데이터를 삭제하는 삭제 기능이 있습니다.

$scope.removeItem = function(index){
        $scope.items.splice(index,1);
    }

이 방법은 뷰에서 주문하기 전에 올바르게 작동합니다.뭔가 중요한 것이 없으면 지금 바로 하게 해주세요.

감사합니다!

대신 또는 로 릴레이합니다.$index- 아시다시피 - 정렬/필터링된 배열의 인덱스를 가리키고 항목 자체를 사용자에게 전달할 수 있습니다.removeItem기능:

<a><img src="img/delete.png" ng-click="removeItem(item)">{{$index}}</a>

변경하다removeItem를 사용하여 인덱스를 찾는 함수indexOf배열 방식은 다음과 같습니다.

$scope.removeItem = function(item){
   $scope.items.splice($scope.items.indexOf(item),1);
}

각을 익히기 시작했고 비슷한 문제에 직면했고, @pkozlowski-opensource의 답변을 바탕으로 다음과 같은 것으로 해결했습니다.

<a>
  <img src="img/delete.png" ng-click="removeItem(items.indexOf(item))">
  {{items.indexOf(item)}}
</a> 

저도 같은 문제가 있어서 이 항목의 다른 답변은 제 상황에 맞지 않습니다.

커스텀 필터로 문제를 해결했습니다.

angular.module('utils', []).filter('index', function () {
    return function (array, index) {
        if (!index)
            index = 'index';
        for (var i = 0; i < array.length; ++i) {
            array[i][index] = i;
        }
        return array;
    };
});

다음과 같이 사용할 수 있습니다.

<tr ng-repeat="item in items | index | orderBy:'Store.storeName'">

그리고 HTML에서 사용할 수 있습니다.item.index대신$index.

이 메서드는 객체 수집에 적합합니다.

이 커스텀 필터는 적용된 모든 필터 목록(orderBy 등)의 첫 번째 필터여야 하며 추가 속성이 추가됩니다.index(이름은 커스터마이즈 가능)를 컬렉션의 각 오브젝트로 만듭니다.

이것을 시험해 보세요.

$scope.remove = function(subtask) {

    var idx = $scope.subtasks.indexOf(subtask),
        st = $scope.currentTask.subtasks[idx];

    // remove from DB
    SubTask.remove({'subtaskId': subtask.id});

    // remove from local array
    $scope.subtasks.splice(idx,1);

}

당신은 내 블로그의 이 항목에서 상세한 설명을 찾을 수 있습니다.

사용할 필요가 있는 경우$index정렬/필터링된 배열에 이름을 지정할 수 있습니다.

<tr ng-repeat="item in sortedItems = (items | orderBy:'Store.storeName') track by $index">

여기서 제 을 보세요.

그냥 댓글을 남겼을 텐데 '평판'이 없어요.

마일의 해결책도 바로 제가 필요했던 것입니다.pkozlowski.opensource 질문에 답하려면: 네스트된 경우ngRepeats, 동적 목록(예를 들어 삭제를 허용하는 경우) 또는 둘 다(내 경우),$index.ngInit이 값은 목록이 변경되어도 다시 캐시되지 않기 때문에 캐시할 수도 없습니다.

mile에서는 파라미터 「」를 해, 할 수 .<tr ng-repeat="item in items | index:'originalPosition' | orderBy:'Store.storeName'">

수정한 버전:

.filter( 'repeatIndex', function repeatIndex()
{
// This filter must be called AFTER 'filter'ing 
//  and BEFORE 'orderBy' to be useful.
    return( function( array, index_name )
    {
        index_name = index_name || 'index';
        array.forEach( function( each, i )
        {each[ index_name ] = i;});
        return( array );
    });
})

언급URL : https://stackoverflow.com/questions/16118762/angularjs-wrong-index-after-orderby

반응형