在angularjs中定义JSON.stringify中的数组长度

时间:2017-10-10 11:07:10

标签: javascript angularjs arrays json

我想在JSON中为send $ http.post保存表单的值  有1个值rooms应该是数组,此数组的长度取决于md-select的值,我应该在每个房间内传递Adulat的值。

var data = {
rooms: [{
    adults: this.adultsHotels,
  }]

我对房间的看法:

<md-select ng-model="rooms" name="numberOfRooms" ng-required="true">
  <md-option ng-repeat="roomsHotel in roomsHotel"
             ng-model="roomsHotel"
             ng-selected = "$first"
             ng-value="roomsHotel.number"
             ng-messages>
            {{roomsHotel.number}}
  </md-option>
</md-select>

和房间的控制器是:

$scope.roomsHotel = ('1 2 3 4 5').split(' ').map(function(roomsHotel) {
    return {number: roomsHotel};
  });

和成人选择视图是:

<md-select ng-model="adultsHotels" name="numberOfAdults" ng-required="true">
    <md-option ng-repeat="adultsHotel in adultsHotel"
               ng-model="adultsHotel"
               value="{{adultsHotel.number}}"
               ng-messages>
                {{adultsHotel.number}}      
    </md-option>
</md-select>

PS: 目标是当选择2个房间时,它增加2个房间,并在每个房间添加成人数量 任何帮助都会非常感激

 "rooms": [
    {
        "adults": "1"
    },
    {
        "adults": "2"
    }
]

1 个答案:

答案 0 :(得分:1)

据我了解您的代码plunker, 您可以使用以下代码修改脚本文件:

// Code goes here


var app = angular.module('app', ["ngMaterial"]);

app.controller('myCtrl', function($scope) {
  $scope.roomsHotel = ('1 2 3 4 5').split(' ').map(function(roomsHotel) {
    return {number: roomsHotel};
  });
  $scope.adultsHotel = ('1 2 3 4 5 6 7 8 9 10 11 12 13 14 15').split(' ').map(function(adultsHotel) {
    return {number: adultsHotel};
  });

  $scope.submitHotelsCtrl = function(response){  
    var rooms = [];
    var totalAdults = parseInt(this.adultsHotels);
    var roomsToFill = parseInt(this.rooms);
     var roomsSelected = parseInt(this.rooms);

    var maxPeopleInRoom = Math.ceil(totalAdults/roomsToFill);      
    for(var j=0; j < roomsSelected; j++){

      if(roomsToFill > 1){
        if(totalAdults >= maxPeopleInRoom){
        var peopleToOccupyInRoom = Math.ceil(totalAdults/roomsToFill);
        totalAdults-=peopleToOccupyInRoom;
        rooms.push({'adults': peopleToOccupyInRoom});
        roomsToFill--;
        }else{
          rooms.push({'adults': totalAdults});    
        }
      }else{
        rooms.push({'adults': totalAdults});  
      }
    }

  var data = {'rooms': rooms
},myObjJSON = JSON.stringify(data);
console.log(data);
console.log(rooms);
}
});

我知道,这段代码可以改进,但同时这应该对你有用,如果问题仍然存在,请告诉我。

plunker link