【问题标题】:Prepopulating checkbox with content from array?使用数组中的内容预填充复选框?
【发布时间】:2013-06-01 15:12:40
【问题描述】:

我有一个复选框,它调用 ng-click 上的函数,该函数插入到 checkedItems 数组中。

如何使用 checkedItems 数组中的元素预先填充此复选框?

以下是我设置中的相关 sn-ps:

<div ng-repeat="c in c_list">
    <input type="checkbox" ng-click="checkSelection(c)"/> {{c}}
</div>
$scope.c_list_selected = []
$scope.checkSelection = function (item) {
    if ($scope.c_list_selected.indexOf(item) === -1) {
        $scope.c_list_selected.push(item);
    } else {
        $scope.c_list_selected.splice($scope.c_list_selected.lastIndexOf(item), 1);
    }
}

我尝试了ng-bindng-model 和一些不同的ng-checked 表达式。没有任何效果。

【问题讨论】:

  • 你想用复选框为checkedItems数组中的每个值预先填充DOM吗?
  • 是的。基本上,如果我勾选了选项[5,'a','b',6] 和默认c_list_selected=[5,'b'];然后我希望在复选框中选择[5,'b'] 值。

标签: javascript angularjs checkbox angularjs-directive angularjs-scope


【解决方案1】:

复选框绑定到布尔值。您必须构建checkedItems 数组的映射(AKA 集),如下所示:

$scope.checkedItemsSet = {};
c_list_selected.forEach(function(item) {
  $scope.checkedItemsSet[item] = true; // populate again
});
$scope.$watch(
  'checkedItemsSet',
  function(newV) {
    var k, v;
    angular.copy([], c_list_selected); // empty the list
    for (k in newV) { // populate again for truey attributes of the mapping
      v = newVal[k];
      if (v) {
        c_list_selected.push(parseInt(k)); // attribute names are indeed strings
      }
    }
  },
  true  // check changes by content instead of by object ID.
);

然后你将每个复选框绑定到集合中的相应项

<input type="checkbox" ng-model="$scope.checkedItemsSet[c]"/>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-20
    • 1970-01-01
    • 2021-05-15
    • 1970-01-01
    • 1970-01-01
    • 2013-11-03
    • 1970-01-01
    • 2019-01-07
    相关资源
    最近更新 更多