我创建了一个表单,在编辑时有多个复选框,该表单复选框是使用以下代码选中的。

视图

<form method="POST" name="LeadCircle" role="form" ng-submit="addLeadCircle()">
  <input type="hidden" ng-model="form.addleadcircle.leadId" name="leadId" />
  <div class="select-basket">
    <div class="checkbox" ng-repeat="circle in circles">
      <input class="checkboxCircle" type="checkbox" ng-checked="{{circle.checked}}" name="leadcircle[]" ng-model="form.addleadcircle.leadcircle[circle.Id]" value="{{circle.Id}}" id="cb-{{circle.Id}}">
      <label for="cb-{{circle.Id}}">{{circle.Name}}</label>
    </div>
  </div>
  <button type="submit" class="btn btn-outline-secondary button-sm text-uppercase pull-right">Add</button>
</form>


AnguarJS

$scope.addLeadCircle = function () {
     console.log($scope.form.addleadcircle);
     return false;
     dataFactory.httpRequest(base_url + 'leadCircles/addLeadCircle', 'POST', {}, $scope.form.addleadcircle).then(function (data) {
         alertify.notify('Assign circle successfully', 'success', 5, function () {});
         return;
     });
}


此代码还显示了选中的复选框,需要检查哪个值。但是如果我尝试提交表单会发生什么,它将不会给出该已选中复选框的值。如果我要选择新复选框,它将给出该新选中复选框的值。

现在在控制台的编辑表单中如果我将不提交任何复选框而直接提交表单,那么它将仅接受尚未选择的隐藏输入值复选框值。如果我选择了新复选框,则仅采用新选择的复选框值。

任何人都可以在此先感谢您的帮助。

最佳答案

您的代码中有几个问题。首先,ng-checked需要一个对象而不是一个字符串。您应该将其更改为ng-checked="circle.checked"。您也不需要value属性,因为ng-model保留您的输入值。我宁愿使用ng-checkedng-init上创建默认值,而不是使用ng-model。这样,您将始终为提交的每个复选框设置一个参数。这也使ng-checked过时,因为ng-model处理“检查”状态。

视图

<div ng-controller="MyCtrl">
  <form ng-submit="submit()">
    <div ng-repeat="item in data">
      <input class="checkboxCircle"
      type="checkbox"
      name="leadcircle[]"
      ng-model="form.addleadcircle.leadcircle[item.id]"
      ng-init="form.addleadcircle.leadcircle[item.id] = item.value" // <- ensure init value
      id="cb-{{item.id}}"> {{item.id}}
    </div>
    <button type="submit">
      Send
    </button>
  </form>
</div>


AngularJS应用

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function($scope) {

  $scope.form = {
    addleadcircle: {
      leadcircle: []
    }
  }

  $scope.data = [{
    id: 1,
    value: true
  }, {
    id: 2,
    value: false
  }, {
    id: 3,
    value: false
  }, {
    id: 4,
    value: true
  }, {
    id: 5,
    value: false
  }, {
    id: 6,
    value: true
  }, {
    id: 7,
    value: true
  }, {
    id: 8,
    value: false
  }];

  $scope.submit = function () {
    console.log($scope.form);
  }
});


>> Demo fiddle

关于javascript - AngularJS确保复选框值设置为初始加载形式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47449150/

10-12 00:06
查看更多