javascript - 如何在 JSON 数组中发布数据

标签 javascript html angularjs json

"type_of_advertisement":["ATM","Banner/Poster","Stalls"]

html代码是

    input(type='checkbox', value='Mobile/Communication Tower', ng-model='type_of_advertisement')
                | Mobile/Communication Tower
              label.checkbox-inline
                input(type='checkbox', value='Banner/Poster', ng-model='type_of_advertisement')
                | Banner/Poster
              label.checkbox-inline
                input(type='checkbox', value='Hoarding Board', ng-model='type_of_advertisement')
                | Hoarding Board
              label.checkbox-inline
                input(type='checkbox', value='Stalls', ng-model='type_of_advertisement')
                | Stalls
              label.checkbox-inline
                input(type='checkbox', value='Digital Offline Marketing', ng-model='type_of_advertisement')
                | Digital Offline Marketing
              label.checkbox-inline
                input(type='checkbox', value='Area for Product Display', ng-model='type_of_advertisement')
                | Area for Product Display

Angular 代码是

type_of_advertisement:[$scope.type_of_advertisement]

出现的问题是当我点击一个复选框时,所有复选框都会自动选择。 并获取 api 响应,例如

"type_of_advertisement":["true"]

那么我可以编写什么代码才能获得所需的 api 结果。

最佳答案

我会通过像这样的数组来解决它:

$scope.rows = [{
    value: "Mobile/Communication Tower"
  }, {
    value: "Banner/Poster"
  }, {
    value: "Hoarding Board"
  }, {
    value: "Stalls"
  }];

和 HTML(在 ng-repeat 内):

<input type="checkbox" ng-model="row.selected" />{{row.value}}</label>

现在,在调用 API 之前,您可以重组数组,如下所示:

$scope.submit = function() {
    $scope.selectedRows = $scope.rows.reduce(function(arr, val) {
        if(val.selected) arr.push(val.value)
      return arr
    }, []);
  };

要让 $scope.selectedRows 成为这样的数组:

[
  "Banner/Poster",
  "Hoarding Board"
]

working example

关于javascript - 如何在 JSON 数组中发布数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43316309/

相关文章:

javascript - 如何在 famo.us 中关闭一个 View 并显示另一个 View

java - 如何检查图像是否可见(Webdriver)

html - css flexbox wrap 属性在 ios6 上不起作用

javascript - 如何将所有左浮动元素对齐到其父元素的中心?

javascript - 如何将值从 json 映射到 Angular View (html)输入文本标签?

javascript - 用户如何在不知道其组成方式的情况下在 AngularJS 中设置元素指令的样式?

javascript - 从当前对象获取属性以在另一个对象中使用该属性值

javascript - 使用 RequireJS 动态添加 Brightcove 视频播放器

javascript - 在可编辑的 div 中插入笑脸

javascript - AngularJS - 在范围更改时使用 if else 语句更改变量值