【问题标题】:how to iterate through checkbox object如何遍历复选框对象
【发布时间】:2017-04-12 22:11:36
【问题描述】:

我有三个复选框:-

<label>Type:</label>
 <label>one</label>
    <input type="checkbox" name="type" ng-model="a.Type[0]"/>

  <label>two</label>
    <input type="checkbox" name="type" ng-model="a.Type[1]"/>

  <label>three</label>
    <input type="checkbox" name="type" ng-model="a.Type[2]"/>

这些复选框以字符串数组的形式存储在后端。

我的价值显示在:-

<li  class="list-group-item"><strong>Type</strong>: <span ng-repeat="values in myArray">{{values}}</span></li>

我的指令代码是:-

    (function () {
    'use strict';
    angular.module('myApp.components')
        .directive('abc', abc);

    abc.$inject = ['$http', '$timeout', 'ApiServices'];

    function abc($http, $timeout, ApiServices) {
        return {
            restrict: 'EA',
            scope: {

            },

            link: function (scope, el, attrs) {
                scope.a = {};

                $('#abc').on('hide.bs.modal', function () {
                    scope.active = false;
                });
                $('#abc').on('shown.bs.modal', function () {
                    scope.active = true;

                    scope.myArray = [];

                  scope.iterate = function () {
                   for (var key in scope.a.Type) {
                      if (scope.a.Type.hasOwnProperty(key)) {
                        scope.myArray.push(scope.a.Type[key]);
                      }
                   }
                  };

                  scope.iterate();
            },
            templateUrl: ''
        };
    }

})();

我想要做的是——我想遍历“类型”复选框并将值推送到“myArray”中,然后只显示这些值。

【问题讨论】:

  • 目前还不清楚您要在这里做什么。您正在为未知指令显示 link 函数,并且链接函数似乎试图通过空对象迭代 instantly。你为什么要遍历数组呢? $scope.a.Type 不是您正在寻找的数组吗?例如你能不做ng-repeat="values in $scope.a.Type"吗?
  • scope.a.Type 在后端的字符串数组中,但是当我保存值时,它们存储为对象,其中键是索引号,值是名称;- 一,二三。所以,我正在做的是遍历该对象并获取值,然后将它们推送到“myArray”中,然后显示数组的值。
  • 但你不是(至少在这段代码中没有)。我不知道你的指令还在做什么,但是这个链接函数设置了scope.a = {};,然后立即尝试遍历它。
  • 我会更新我的代码。但这里我只展示必要的代码,函数是迭代它。
  • 对,但您没有展示 scope.a 如何从 {} 变为其中包含任何数据。

标签: javascript angularjs html angularjs-ng-repeat


【解决方案1】:

可能,我下面的示例与您要查找的内容有些相似:

HTML:

  <span>Select Type:</span>
  <div ng-repeat="type in myArray">
    <input type="checkbox" ng-model="type.value" /> {{type.type}}
  </div>

  <span>Selected Types:</span>
  <div ng-repeat="type in myArray">
    <span ng-show="type.value"> {{type.type}}</span>
  </div>

JS:

  $scope.a = {};
  $scope.a.Type = ["One","Two","Three"]; // your string array

  $scope.myArray = [];
  $scope.a.Type.forEach(function(item){
    $scope.myArray.push({type: item, value: false }); // create new array to make it selectable via checkbox
  });

我猜,你现在不再需要你的指令了。迭代和过滤是在 HTML 本身中完成的。

我希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2012-11-12
    • 1970-01-01
    • 2011-03-16
    • 1970-01-01
    • 1970-01-01
    • 2021-05-08
    • 2013-01-01
    • 2019-06-07
    • 1970-01-01
    相关资源
    最近更新 更多