2016-04-29 45 views
2

當我點擊按鈕的值將推到另一個數組。接下來,我點擊相同的按鈕,推送項目將被刪除。 在我的項目中推送完成正確。但第二次單擊相同的按鈕數組中刪除的第一個元素不是選定的一個。使用拼接刪除數組無法正常工作?

這是我的HTML代碼。

<a class="btn {{table.btnClass}} btn-success" ng-click="getTable(table)" style="padding-left:1px">{{table.tablename}}</a> 

這是我的控制器代碼

$scope.tableArray=[] 
$scope.tableslist=[] 
$scope.getTable=function(table){ 
    table.btnClass = table.btnClass == "btn-danger" ? "btn-success" : "btn-danger" 
    console.log(table) 
    var exists=false; 
    angular.forEach($scope.tableArray, function (list) { 
     if ((list.tablename == table.tablename)) { 
      console.log(list.tablename) 
      console.log(table.tablename) 
      exists=true; 
      $scope.tableArray.splice(list._id,1) 
      return false 
     } 
    }); 
    if(!exists){ 
    $scope.tableslist.push(table) 
    $scope.tableArray=$scope.tableslist 
    console.log($scope.tableArray) 
    table.color="red" 
    } 
} 

請幫我

回答

3

加入的foreach第二個參數,使用索引從陣列拼接

angular.forEach($scope.tableArray, function (list, index) { 
    ---------- 
    ------------------- 
    $scope.tableArray.splice(index,1) 
}) 
+0

感謝您的建議。爲我工作。 – SrinivasAppQube

0

對於刪除所選項中的數組可以使用indexOf,如下所述。

$scope.tableArray.splice($scope.tableArray.indexOf(list),1);   
0

遇到了與Splice類似的問題。在我的情況下,如果它幫助某人,我必須解決下面的問題。

如果您正在處理對象,請注意indexOf適用於數組而不適用於該數組內的對象。你可以做下面的事情來確定索引並處理這個案例;

$scope.removeReport = function(report) { 
    var index = $scope.contact.reports.map(function(r) { return r.id;}).indexOf(report.id); 
     if (index >= 0) { 
      $scope.contact.reports.splice(index, 1); 
     } 
}