2016-02-01 22 views
0

我試圖創建一個菜單,其中有多個選項,可以使用checkboxesAngularJS中選擇。 我用我的邏輯中使用的兩個屬性來模擬我的DB; min_selection_pointsmax_selection_points。我的想法是,我將使用這些來跟蹤我的checkboxes已被選中的數量,一旦達到max_selection_points,我將禁用checkboxes的其餘部分。用ng-repeat處理多個複選框 - AngularJS

因此,假設我有6 checkboxesmax_selection_points = 2,當2個複選框被選中我禁用4剩餘checkboxes 1時,將取消然後我重新啓用它們都是因爲選擇的數量未達到2這是最大。我打算使用min_selection_points作爲驗證當button被按下,所以我希望能夠計數檢查框的數量,或者當達到max_selection_points時設置bool ......這是我迄今爲止的代碼;

<div class="group-items" ng-if="modifier.max_selection_points > 1 || (modifier.max_selection_points == 1 && modifier.min_selection_points == 0)"> 
    <div ng-repeat="item in modifier.menu_modifier_items" class="modifier-item multiple"> 
     <label for="<%modifier.id + '_' + item.id%>"> 
      <input id="<%modifier.id + '_' + item.id%>" 
        class="checkbox-branded" 
        type="checkbox" 
        name="<%item.name%>" 
        ng-model="item.selected" 
        ng-class="{'not-available': !item.available}" 
        title="<%item.name%>" 
        value="<%item.id%>"> 
    <span class="item-name"> 
     <span ng-bind="item.name"></span> 
     <span ng-bind="priceDelta(modifier, item)"></span> 
    </span> 
     </label> 
    </div> 
</div> 

我相信我會需要使用ng-clickng-change實現這個邏輯,所以我有:

ng-click="modifierClicked(item)" 
ng-change="modifierSelected(item)" 

任何指導讚賞

回答

0

你可以有一個返回值的檢查數的函數複選框:

$scope.Checked = function() { 
    var count = 0; 
    angular.forEach($scope.modifier.menu_modifier_items, function(item){ 
     count += item.selected ? 1 : 0; 
    }); 
    return count; 
} 

T母雞你可以有一個NG-禁用每個輸入:

ng-disabled="!item.selected && Checked== modifier.max_selection_points" 

你可以試試這個plunker

0

前面的回答提出的盧卡斯·羅德里格斯的權利,但plunker是怪異。

$scope.max_selection_points = 2; 
 

 
$scope.questions = [{ 
 
    id: 21, 
 
    answer: "Chicago" 
 
}, { 
 
    id: 22, 
 
    answer: "New York" 
 
}, { 
 
    id: 23, 
 
    answer: "Los Angeles" 
 
}, { 
 
    id: 24, 
 
    answer: "London" 
 
}, { 
 
    id: 25, 
 
    answer: "Moskva" 
 
}]; 
 
$scope.countChecked = function() { 
 
    var count_ = 0; 
 
    angular.forEach($scope.questions, function(quest) { 
 
    if (quest.checked) 
 
     count_++; 
 
    }); 
 
    return count_; 
 
}
<div ng-repeat="question in questions"> 
 
    <label> 
 
    <input ng-disabled="!question.checked && max_selection_points==countChecked()" type="checkbox" ng-model="question.checked">{{ question.answer }} 
 
    <br/> 
 
    </label> 
 
</div>

這是正確plunker