问题
I am working on a school project where a user can choose what items he/she can borrow from the school's computer services office. I have completed the application form where the student/faculty can insert their profile information. I am having issues regarding the checkboxes in AngularJS.
I need to total/sum up the IDs of the checkboxes so that it can be inserted into the database as a single int, not an array. Here are the code and some information.
$scope.chkItems = [
{
id: 1,
name: 'Laptop',
value: null,
}, {
id: 2,
name: 'Headset',
value: null
}, {
id: 4,
name: 'Projector',
value: null
}, {
id: 8,
name: 'Tablet',
value: null
}, {
id: 16,
name: 'Speakers',
value: null
}];
$scope.save = function () {
var chkItemsValue = '';
$scope.chkItems.forEach(function (Item) {
if (Item.value) {
chkItemValue += chkItem.id;
}
})
}
<md-input-container class="md-block" flex-gt-sm>
<label class="force-input-label">Items</label>
</br>
<div ng-repeat="chkItem in chkItems">
<md-checkbox name="chkItem.name" ng-model="chkItem.value" ng-true-value=1 ng-false-value=0>{{chkItem.name}}
</div>
</md-input-container>
I can insert the value on the database but the value is different instead of getting the total the value I get an array like output.
- Currently, I am getting this:
if I check {Laptop, Projector, Speakers} the total would be 1416
- What I want:
if I check {Laptop, Projector, Speakers} the total would be 21
I am new to AngularJS and web development. Your inputs are greatly appreciated!
ThankYOU!
回答1:
Quick answer, don't initialise your counter as a string
var chkItemsValue = 0 // not ''
Array.prototype.reduce answer
var chkItemsValue = $scope.chkItems.reduce((count, item) => {
return count + (item.value ? item.id : 0)
}, 0)
来源:https://stackoverflow.com/questions/42016551/how-to-add-ids-of-a-checkbox-in-angularjs