How to add IDs of a checkbox in AngularJS?

非 Y 不嫁゛ 提交于 2020-01-04 06:44:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!