数据绑定到复选框内的 ng-model

Data-binding to ng-model inside of checkbox

我的问题是我试图从控制器内部访问这些复选框,以便我可以从那里将它们设置为 true。

出于某种原因,我无法找出用于这些复选框的正确 ng-model 以便我能够这样做,同时保持每个复选框都有一个唯一的名称。

       <accordion-group ng-repeat="group in groups">
        <accordion-heading>{{group.title}}</accordion-heading>
        <div ng-repeat="collection in group.collections">
          <div class="checkbox collection-legend" style="background-color: {{collection.color}}">
            <label><input type="checkbox" ng-click="toggleCollection(collection.key)" ng-model="checkboxes[collection.key]"> {{collection.name}}: <em>{{collection.description}}</em></label>
            <div class="customFields">
              <label ng-repeat="(key, val) in collection.queries" ng-if="key != 'default' && key != 'dateRangeKey'">
              <input class="form-text" ng-model="customProperties[collection.name + '-' + key]" type="text"><em>{{key}}</em></label>
            </div>
          </div>
        </div>
      </accordion-group>

对于某些上下文,我正在尝试设置一个 "restore session" 方法,用户可以在其中恢复提交的旧表单而无需再次填写它们,所以我有一个复选框列表需要 "rechecked",我只是不知道如何命名我的模型,所以我可以做到。

ng-model="checkboxes[collection.key]" 似乎应该在这里工作。有什么建议吗?

然后在控制器中$scope.checkboxes[key] = true。 (键匹配 collection.key;我已经确认了这一点)。出现 "can not set (key) of undefined" 错误。

这是JS:

    $scope.session.collections.forEach(function(c){
      $scope.toggleCollection(c);
      console.log(c + ' '+ typeof c);
      $scope.checkboxes = {
        c: true
      };
    });

解决方案:从未将 $scope.checkboxes 初始化为空对象。现在可以使用了。

你粘贴的代码确实有效,我在这里验证过: https://jsfiddle.net/ho8art1t/

复选框应该符合这些原则:

$scope.checkboxes = {
    a: true,
    b: false,
    c: true
};

您应该粘贴随附的 JS,或者检查您的对象的放置方式是否与 fiddle 中的类似。