将第二个或更多数组推入数组对象angularjs

时间:2015-03-13 13:26:12

标签: javascript arrays angularjs



angular.module('print', []).
controller('Ctrl', function($scope) {
  $scope.settingData = [{
    "currency": "RM",
    "fields": {
      "type": "",
      "cost": "",
      "pax": "1"
    }
  }]

  $scope.addNewFields = function() {
    var row = $scope.settingData.length;
    if (row < 3) {
      $scope.settingData.push(row);
    }
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>

<div ng-app="print" ng-controller="Ctrl ">
  <button ng-click="addNewFields()">Add</button>
  <br />
  <br />
  <div class="editSection">
    <div class="inputRowWrap" ng-repeat="data in settingData">
      {{data.fields.type}} {{data.fields.cost}} {{data.fields.pax}}
      <div class="row">
        <div class="col col-40">
          <label class="item item-input">
            <input type="text" placeholder="Room Type #{{$index+1}}" ng-model="data.fields.type">
          </label>
        </div>
        <div class="col col-40">
          <label class="item item-input">
            <input type="text" placeholder="RM" ng-model="data.fields.cost">
          </label>
        </div>
        <div class="col">
          <select ng-model="data.fields.pax">
            <option>pax</option>
            <option value="1">1 pax</option>
            <option value="2">2 pax</option>
          </select>
        </div>
      </div>
    </div>
    <div class="padding saveBtnWrap">
      <button ng-click="saveSetting()">Save</button>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

我管理推送添加新的html,但新的输入不起作用,我想我未能将新的数组对象添加到现有的数组对象中。

2 个答案:

答案 0 :(得分:0)

if (row < 3) {
    $scope.settingData.push(row);
}

将整数推入对象数组。我已经更新了你的小提琴:https://jsfiddle.net/mkcegb80/1/

答案 1 :(得分:0)

而不是将索引推入数组,我们需要推送一个对象。

angular.module('print', []).
controller('Ctrl', function($scope) {
  var data = {
    "currency": "RM",
    "fields": {
      "type": "",
      "cost": "",
      "pax": "1"
    }
  }

  $scope.settingData = [angular.copy(data)]

  $scope.addNewFields = function() {
    var row = $scope.settingData.length;
    if (row < 3) {
      // create a copy of the data object and push into the array
      $scope.settingData.push(angular.copy(data));
    }
  }
});