2014-10-08 73 views
0

我使用angularjs爲我的項目和它的工作正常。今天我面臨的只是一點但不同的問題 所以只需要一些建議。 考慮代碼:拼接後Angularjs數組更改引用

$scope.deleteEmpty = function(){ 

    for(var sp=0;sp < $scope.column.length;sp++){ 

     var offerings = $scope.column[sp]; 

     if(offerings.spName == -1){ 

      $scope.removeanswer(sp);       
     } 
    } 
}, 

$scope.removeanswer = function(position){ 

    for(var question=1;question<$scope.rows.length;question++){ 

     $scope.rows[question].answerlst.splice(position, 1); 
    } 
}, 

在這裏,我根據產品位置刪除answerlst,它是越來越刪除,但有一個問題。考慮一個例子:

$scope.column = [{'spName':'-1',spId:'1'},{'spName':'-1',spId:'2'},{'spName':'-1',spId:'3'},{'spName':'-1',spId:'4'}] 

當第一次調用$scope.removeanswer(sp);它刪除answerlst的第一列但的answerlst位置得到改變之後。所以它刪除了第一和第三的位置,而不是整體。

請任何建議。 謝謝。

+0

什麼是$ scope.rows? – 2014-10-08 13:13:30

+1

建議您在jsfiddle.net或plnkr.co中創建一個演示,以複製您的問題。很難理解你的描述中的問題。我們也無法看到你在哪裏調用deleteEmpty()從 – charlietfl 2014-10-08 13:14:01

+0

@ Robin Elvin問題,並在其中包含答案列表。 – user3406754 2014-10-08 13:14:09

回答

0

如果有更多信息,可以改進以下解決方案。

這個想法是將列索引存儲在toRemove數組中,然後從每個問題的answerlst一次全部刪除它們。

$scope.deleteEmpty = function(){ 
    var toRemove = []; // column indexes to be removed 

    for(var sp=0;sp < $scope.column.length;sp++){ 
     var offerings = $scope.column[sp]; 
     if(offerings.spName == -1){ 
      toRemove.push(sp);       
     } 
    } 
    $scope.removeanswer(toRemove); 
}, 

$scope.removeanswer = function(positions){ 
    for(var question=1;question<$scope.rows.length;question++){ 
     $scope.rows[question].answerlst = $scope.rows[question].answerlst.filter(function(value, index) { 
      return positions.indexOf(index) < 0; 
     }); 
    } 
}, 
+0

感謝您的回覆,它效果很好。 – user3406754 2014-10-09 05:11:32