如何在AngularJS中添加复选框的ID? [英] How to add IDs of a checkbox in AngularJS?

查看:89
本文介绍了如何在AngularJS中添加复选框的ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个学校项目,用户可以在其中选择可以从学校计算机服务办公室借用的物品。我已经填写了申请表格,学生/教师可以在其中插入他们的个人资料信息。我在AngularJS中遇到有关复选框的问题。

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.

我需要总计/总结复选框的ID,以便可以将其作为单个int插入数据库中。 ,而不是数组。这是代码和一些信息。

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.


  • 当前,我得到的是:

如果我检查{笔记本电脑,投影仪,扬声器}
总共是1416

if I check {Laptop, Projector, Speakers} the total would be 1416


  • 我想要的东西:

如果我勾选{笔记本电脑,投影仪,扬声器}
总共是21

if I check {Laptop, Projector, Speakers} the total would be 21

我是AngularJS的新手和网站开发。

I am new to AngularJS and web development. Your inputs are greatly appreciated!

谢谢!

推荐答案

快速解答,不要将您的计数器初始化为字符串

Quick answer, don't initialise your counter as a string

var chkItemsValue = 0 // not ''






Array.prototype.reduce 答案

var chkItemsValue = $scope.chkItems.reduce((count, item) => {
    return count + (item.value ? item.id : 0)
}, 0)

这篇关于如何在AngularJS中添加复选框的ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆