【问题标题】:Deleting an item by $index or indexOf() results in deleting all items in ng-repeat通过 $index 或 indexOf() 删除一个项目会导致删除 ng-repeat 中的所有项目
【发布时间】:2015-03-26 18:51:05
【问题描述】:

我有一个离子列表,其中包含来自指令 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;
};

【问题讨论】:

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


    【解决方案1】:

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

    见:http://www.w3schools.com/jsref/jsref_splice.asp

    【讨论】:

      【解决方案2】:

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

      Array.splice(index, amount) 
      

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

      【讨论】:

        猜你喜欢
        • 2020-02-11
        • 1970-01-01
        • 1970-01-01
        • 2016-06-02
        • 1970-01-01
        • 1970-01-01
        • 2015-12-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多