I have checkboxes within loop like below:
<li ng-repeat="item in items">
<h2> {{item.better}}</h2>
<span>{{item.startTime}}</span>
<b> {{item.lengthTime}}</b>
<input type="checkbox" checklist-model="item.winner" checklist-value="item">
</li>
I want to set limit so that users could only select maximum 50 checkboxes and not more than that out of (no. of total items in the list i.e 100 or 200 etc.).
How do we accomplish that using angular js ?
Help would be really appreciated.
Thank you.
We will use the Angular JS directive named ng-disabled to disable the button by unchecking the box. Please refer to AngularJS ng-disabled Directive. The ng-disabled directive is used to enable or disable the HTML elements.
You can use the [disable] attribute your input[type="checkbox"] tag. For larger, more complex forms I highly recommend using a reactive form. With a reactive form, you can use [disabled]="condition" where the condition is something like whateverCheckbox.
FIDDLE
$scope.checkChanged = function(item){
if(item.winner) $scope.checked++;
else $scope.checked--;
}
and
<input type="checkbox" ng-model="item.winner" ng-change="checkChanged(item)" ng-disabled="checked==limit && !item.winner"/>
this keeps track of checked with ng-change and disables them if the limit is reached and the checkbox is not checked.
not using $watch because of the possibility of ~200 checkboxes.
edit: sorry forgot to click update on fiddle, it should work now. Also note that limit is set to 4 with $scope.limit = 4
;
you could ask for the number of items and use the ng-disabled
<input type="checkbox" ng-disabled="!item.value && items.length > 50" />
as mentioned in the comments, the answer is not correct. But i think you got (and other guys who answered) the right idea how to accomplish what you need. I think, the necessary information for you is to use ng-disabled
.
I like Aperçu answer most :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With