动态表单字段与angularjs中的复选框

时间:2016-12-10 15:24:33

标签: javascript html angularjs checkbox ionic-framework

我想使用ng-submit将输入字段的值提交给控制器,但是当我控制台输入模型时,它显示未定义。每个输入值都与复选框一起保存。但我想检查是否取消选中任何复选框。 这是表格html:

<form id="valueForm" ng-submit="submitValues()">
    <div class="small-input list padding" style="padding-top:4px;">
        <div ng-repeat="item in inputs  track by $index">
            <label class="item item-input">
                    <input type="text"  placeholder="" ng-model="value" ng-disabled="ticked">
                    <ion-checkbox ng-click="addField($index)"  ng-change="saveValue(ticked,value,$index)" ng-model="ticked"  
                           ng-disabled="!value" style="border: none;padding-left: 30px;" class="checkbox-royal"></ion-checkbox>
            </label>
        </div>
    </div>
    <button type="submit" ng-show="showButton" class="button button-dark button-shadow pull-right" style="" ><i class="ion-ios-arrow-forward"></i></button>
    </form>

这是控制器:

 $scope.showButton = false;
  $scope.inputs = [{value:''}];
  var checkedValues =[];
  $scope.addField = function (index) {
      if($scope.inputs.length <= index+1 && $scope.inputs.length<10){
                  $scope.inputs.splice(index+1,0,name);
      }
  }
  $scope.saveValue = function (ticked,item,index) {

    if(ticked){
      console.log('index'+index);
      if(index>0) $scope.showButton =true;
      checkedValues.splice(index,0,item);
      console.log(checkedValues);
    }else{
      checkedValues.splice(index,1);
      console.log(checkedValues);
    }

  }
  $scope.submitValues = function(){
    console.log($scope.value);
  }

1 个答案:

答案 0 :(得分:1)

由于输入和复选框位于ng-repeat指令内,因此ng-model值必须是item迭代器的属性。

<form id="valueForm" ng-submit="submitValues()">
    <div ng-repeat="item in inputs  track by $index">
         <!-- REMOVE
         <input type="text" ng-model="value" ng-disabled="ticked">
         <ion-checkbox ng-model="ticked"> </ion-checkbox>
         -->
         <!-- INSTEAD -->
         <input type="text" ng-model="item.value" 
                ng-disabled="item.ticked">
         <ion-checkbox ng-model="item.ticked"> </ion-checkbox>
    </div>
    <button type="submit" ng-show="showButton"> 
        <i class="ion-ios-arrow-forward"></i>
    </button>
</form>

ng-repeat指令为每个项目创建子范围。使用没有&#34;点&#34;的值将值放在每个子范围上。因此规则:&#34;总是使用&#39; dot&#39;你的ng-models&#34;。

有关详细信息,请参阅AngularJS Wiki -- The Nuances of Prototypical Inheritance

<强>更新

要查看提交时的输入:

  $scope.submitValues = function(){
    //console.log($scope.value);
    console.log($scope.inputs);
  }