AngularJS确保在初始加载的表单中设置复选框值

时间:2017-11-23 06:43:40

标签: javascript html angularjs

我已经创建了一个表单,在编辑时有多个复选框,表单复选框即将使用以下代码进行检查。

视图

<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;
     });
}

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

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

任何人都可以提前帮助,谢谢。

1 个答案:

答案 0 :(得分:1)

您的代码中存在一些问题。首先,ng-checked需要一个对象而不是一个字符串。您应该将其更改为ng-checked="circle.checked"。您还不需要value属性,因为ng-model会保留您的输入值。我宁愿使用ng-checked在您的ng-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);
  }
});

<强>&GT;&GT; Demo fiddle