【问题标题】:How do I retrieve a list of all checked items using AngularJS?如何使用 AngularJS 检索所有检查项目的列表?
【发布时间】:2017-09-19 12:15:49
【问题描述】:

我正在尝试更改同步 (Using <input type="checkbox">) 的 this AngularJS 示例的功能以返回对象数组。

在我的 html 中,我使用 ng-repeat 和 AngularJS 演示示例中的一些函数调用有以下代码:

<div ng-repeat="item in items" class="standard" flex="50">
      <label> <input type="checkbox" ng-checked="exists(item, selected)" /> {{item.name}} </label>
</div>

我还有一个按钮可以选择或删除所有复选框条目:

 <label> <input type="checkbox" ng-checked="isChecked()" ng-click="toggleAll()" autofocus ng-model="checkbox" ng-change='delayedSearch(0)'/>
        <span ng-if="!isChecked()">all</span>
        <span ng-if="isChecked()">nothing</span>
  </label> <br><br>

在我的控制器中,我按如下方式初始化数组项:

$scope.items = [{name:'K://',value:'nemo'},{name:'Bugzilla',value:'bugzilla'},{name:'Jira',value:'jira'}];

以及与复选框交互的相应函数:

    $scope.toggle = function (item, list) {
            var idx = list.indexOf(item);
            if (idx > -1) {
                    list.splice(idx, 1);
                    if (list.length == 0){
                            list.push('nothing');
                    }
            }else {
                    var id = list.indexOf('nothing');
                    if (id > -1) {
                            list.splice(id,1);
                    }
                    list.push(item);
            }
    };

    $scope.exists = function (item, list) {
            return list.indexOf(item) > -1;
    };

    $scope.isChecked = function() {
            return $scope.selected.length === $scope.items.length;
    };

    $scope.toggleAll = function() {
            if ($scope.selected.length === $scope.items.length) {
                    $scope.selected = ['nothing'];
            } else if ($scope.selected.length === 0 || $scope.selected.length > 0) {
                    $scope.selected = $scope.items.slice();
            }
    };

目前我的代码返回所有选中项的对象列表,例如:

[{"name":"K://","value":"nemo"},{"name":"Bugzilla","value":"bugzilla"},{"name":"Jira","value":"jira"}]

我想获得一个列表,其中仅包含所有检查项目的值,如下所示:

["nemo","bugzilla","jira"]

【问题讨论】:

  • 为什么不推送值而不是对象?
  • 然后我得到了单次切换的正确结果,但 toggleall 仍然返回对象
  • 您可以循环或使用以下答案来获取全部切换的所有值
  • 最后一件事.. 如果我的列表是空的,如何将其设置为 [{"name":"nothing","value":"nothing"}]?
  • if (!list.length) { list.push({"name":"nothing","value":"nothing"}) }

标签: javascript angularjs angularjs-material


【解决方案1】:

您可以像这样映射结果列表:

   var valuesArray =  [{"name":"K://","value":"nemo"},{"name":"Bugzilla","value":"bugzilla"},{"name":"Jira","value":"jira"}].map(function(obj) {
      return obj.value;
    }); // ["nemo","bugzilla","jira"]

【讨论】:

  • 地图是个很强大的小东西,非常感谢解决了我所有的问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多