2015-06-13 37 views
0

我是angularjs的新手,我正在開發一個應用程序。我在複選框中遇到問題。選擇複選框會輸出正確的數組元素,但是問題在於當我取消選擇它們時。元素只是將自己添加回數組中。對不起,如果我不解釋自己...我認爲需要發生的是從數組中刪除選定的複選框,如果它沒有選中。我是否錯過了某處的循環,或者是否需要添加$ watch ?.我一直試圖解決這個問題好幾個小時了! 任何建議/幫助將不勝感激。謝謝。AngularJS複選框問題

Here is the code: 

HTML: This is the select/unselect on table header. 

<td class="checkbox-selector"> 
           Select All 
           <input type="checkbox" 
             ng-model="selectedAll" 
             ng-click="checkAll()"> 
          </td> 

    ..and the individual checkboxes: 



<td> 
          <input type="checkbox" 
            class="checkbox-row" 
            ng-model="result.isSelected" 
            ng-click="selectedShop(result.shopName, result.ItemId)" /> 
          </td> 

Angularjs: 

$scope.allSelection = []; 

    $scope.checkAll = function() { 
     if ($scope.selectedAll) { 
      $scope.selectedAll = false; 
     } else { 
      $scope.selectedAll = true; 
     }  
     angular.forEach($scope.results, function (result) { 
      result.isSelected = $scope.selectedAll; 
      $scope.allSelection.push("result.shopName"+"result.itemId");   

      $scope.allSelection=[]; 

     }); 
    }; 


$scope.selection=[]; 

$scope.selectedShop = function selectedShop(shopName, itemId) { 
    $scope.selection.push("shopName"+ "itemId"); 

}; 

回答

0

這個問題看起來相當簡單,通過調試#checkAll函數就可以解決。

而且一目瞭然,它看起來像有在#checkAll重複犯的一個錯誤 - 我認爲你的目的是要清理allSelection第一(外的forEach),然後有條件地添加所有項目(如果選擇)。

事情是這樣的:

$scope.checkAll = function() { 
    $scope.selectedAll = !$scope.selectedAll; 
    $scope.allSelection=[]; 
    angular.forEach($scope.results, function (result) { 
     result.isSelected = $scope.selectedAll; 
     if ($scope.selectedAll) { 
      $scope.allSelection.push(/*whatever needs to be in that array*/);   
     } 
    }); 
} 

另一個建議是提取不正常工作的一部分(可能在共享的jsfiddle)。

+0

嗨Arturs,我想你已經解決了我的問題 - 通過清理allSelection。我認爲必須在最後...如果我遇到更多的問題,我會分享JSFiddle,我相信我會.. ..萬分感謝您的幫助,真的很感謝:)! – 1313

+0

接受:)再次感謝Arturs! – 1313