简体   繁体   中英

How to Adjust index when doing array splice

I have a photo manager that breaks in the view when I delete an index that is NOT the last index

Model:

var array = [{id:1, img:"index0"},{id:2, img:"index1"},{id:3, img:"index2"}]

if i do..

array.splice(0);

index 1 and 2 will be hidden, so when I investigated i learned that index 1 and 2 doesn't adjust to index 0 and 1, that's probably the reason why it's breaking in the view since i'm using a ng-repeat, how do i workaround this issue.

  <div class="col" ng-repeat="pic in pics track by $index">
    <img ng-click="delete()" ng-src="https://s3-ap-southeast-1.amazonaws.com/sample/posts/{{pic.id}}/{{pic.img}}.jpg"></img>
  </div>

controller:

//HTTP REQUEST --> for brevity i didn't include the service
    $scope.delete = function(){
    PostService.DeletePic()
      .success(function (data) {
     $scope.pics.splice(index);
              }).
            error(function(error,status) {

          }) 
    }

Calling array.splice(0); will not remove any element from the array.

Syntax: array.splice(start, deleteCount[, item1[, item2[, ...]]])

deleteCount An integer indicating the number of old array elements to remove. If deleteCount is 0, no elements are removed. In this case, you should specify at least one new element. If deleteCount is greater than the number of elements left in the array starting at start, then all of the elements through the end of the array will be deleted.

( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice )

You need to call array.splice(0, 1); to remove the first element. This should fix your 'index not adjusting' problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM