javascript - 从复选框循环遍历 json 对象

标签 javascript json angularjs

我有一个 json 对象,正在通过 ng-repeat 中的复选框加载。它列出了可能的服务,我正在尝试访问提交表单时已检查的服务。

我通过以下方式加载复选框:

<label style="margin-right:10px" ng-repeat="item in dsServces">
    <input
        type="checkbox"
        name="selectedFruits"
        value="{{item.DefaultServiceID}}"
        ng-model="expense.dsService[item.DefaultServiceName]"
    > {{item.DefaultServiceName}}
</label>

我可以通过测试看到费用正在建立:

{{ expense.dsService }}

返回(当选择一对时)

{"Email":true,"Backups":true}

但我不知道如何循环,所以它只显示服务名称,以便我可以针对客户添加它们。

在后端我有:

$scope.expense = {
    tags: []
};

提交时:

 angular.forEach($scope.expense, function(item) {
    console.log(item);
});

其中输出 Object {Email: true, Backups: true} 但我无法找到一个循环,它只返回哪个对象为 true。

我的主要目标是拥有类似的东西

angular.forEach(forloop) {
    //service.item should be like 'Email' whatever the item.DefaultServiceName is
    // the loop should be all items that are checked
    addService(service.item);
});

最佳答案

如果我理解正确,您希望将对象的键值插入数组中。如果是这种情况,只需对您的 forEach()

进行一些更改即可

像这样:

// The first parameter is what you want to loop through
// Second is the iterator, you can separate out the key and values here
// The third is the context, since I put the array we want to push to in here
// we just need to call `this.push()` within the iterator
angular.forEach($scope.expense, function(value, key) {
  this.push(key);
}, $scope.expense.tags);

请告诉我这是否有帮助。

关于javascript - 从复选框循环遍历 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27062233/

相关文章:

javascript - 在 Ext.js/Sencha Touch 中显示数学符号

javascript - new String() 的行为不像对象那样的数组

javascript - 为什么我的 javascript 添加类将图像显示设置为无时不起作用?

json - 我的 JSON 解码器不工作,我不确定为什么

javascript - 从 Angular 范围内的数组值显示单选按钮数据

JavaScript - Math.random() - 参数

javascript - JSON 请求包含在另一个 JSON 中?

jquery - 将新的键值对推送到 json

javascript - 是否可以将 'required' 传递给 AngularJS 指令?

javascript - Jade 转 HTML 未定义字段