通过$ index或indexOf()删除项目会导致删除ng-repeat中的所有项目

时间:2015-03-26 10:43:01

标签: javascript angularjs angularjs-ng-repeat ionic-framework

我有一个离子列表,其中的项目包含指令ion-delete-button中的属性(参见docs)。

我在以下事项中使用ng-repeat填写列表:

HTML

<ion-list>

<ion-item class="item item-thumbnail-left item-text-wrap" 
                ng-repeat="albumname in Albums track by $index" 
                href="#/tab/dash/{{Albums[$index]}}">

                <img ng-src="{{thumbnailImage(albumname, 'album')}}" class="thumbnail-album">

                <h2 style="padding-top: 20px">{{albumname}}</h2>

                <!--WORKS FINE, CHANGES NAME OF $index -->
                <ion-option-button class="button-energized"   ng-click="changeAlbumName($index)">Change Name</ion-option-button> 

                <!-- DOES NOT WORK AS EXPECTED, ON PHONE DELETES ALL ALBUMS -->
                <ion-delete-button class="ion-minus-circled"  ng-click="deleteAlbum($index)"></ion-delete-button> 

      </ion-item>

</ion-list>

控制器

// Initialized and Refreshed on Updates
$scope.Albums = DashFactory.getAlbums();

$scope.deleteAlbum = function(index) {
    console.log(index) // SHOWS CORRECT INDEX
    var confirmPopup = $ionicPopup.confirm({
      title: 'Delete Album: ' + $scope.Albums[index],
      template: 'Are you sure you want to delete this album?'
    });
    confirmPopup.then(function(res) {
      if(res) {
        console.log('You are sure');
        DashFactory.deleteAlbum(index); // SERVICE FOR DELETING THE ALBUM
        $ionicListDelegate.showDelete(false);
      } else {
        console.log('You are not sure');
      }
    });
  }

服务(DashFactory)

var Albums = ['foobut', 'barplug', 'fooin', 'barass']

var deleteAlbum = function(index) {
        Albums.splice(index);
        this.saveAlbums();
};
var getAlbums = function() {
        return Albums;
};

2 个答案:

答案 0 :(得分:1)

Array.splice需要多个参数,现在它将从你给出的索引开始删除所有内容。试试Album.splice(index,1);

请参阅:http://www.w3schools.com/jsref/jsref_splice.asp

答案 1 :(得分:0)

解决了它。基本上你必须写:

Array.splice(index, amount) 

其中金额为1,即您要删除的项目数。否则它将全部删除。