Trialcoder
Trialcoder

Reputation: 6004

Unable to create dynamic array of objects in AngularJS

Following is the type of array I am trying to create(avail) on button click -

    [
        {DATE, morning_VALUE, night_VALUE},
        {DATE, morning_VALUE, night_VALUE},
        {DATE, morning_VALUE, night_VALUE},
        {DATE, morning_VALUE, night_VALUE},
        {DATE, morning_VALUE, night_VALUE},
        {DATE, morning_VALUE, night_VALUE},
        {DATE, morning_VALUE, night_VALUE},
    ]
    morning_VALUE -> true/false
    night_VALUE -> true/false

Following is my plnkr code - PLNKR

HTML -

<div class="col-lg-3">
  <ul>
    <li ng-repeat="a in weeklist" style="margin-bottom: 3px;">
      <button ng-click="showWeekDays(a[0], a[1])" 
              style="width:178px;" 
              class="btn bg-blue">
        {{a[0] | date: 'shortDate'}} - {{a[1] | date: 'shortDate'}}
      </button>
    </li>
  </ul>
</div>
<table>
  <tr ng-repeat-start="a in sevenWeekDayArr">
    <td>
      {{a | date: 'shortDate'}}
    </td>
    <td>
      <input type="hidden" 
             ng-model="avail[$index].currDate" 
             ng-init="avail[$index].currDate = a" />
    </td>
  </tr>
  <tr>
    <td>Morning:</td>
    <td>
      <input type="checkbox" ng-model="avail[$index].morning" />
    </td>
  </tr>
  <tr ng-repeat-end="">
    <td>Night:</td>
    <td>
      <input type="checkbox" ng-model="avail[$index].night" />
    </td>
  </tr>
</table>
<div>
  <button ng-click="addTime(avail)">Click</button>
</div>

Let me know what I am doing wrong here, I believe I need to use push in the case but don't know how to fit it in my scenario.

Upvotes: 1

Views: 3039

Answers (2)

khizar naeem
khizar naeem

Reputation: 296

You're trying to bind object to a model object that does not have certain values.

try this after line 17 in script.js

$scope.avail.push({currDate: "", morning:false, night:false}); 

this will initialize that array of objects and then you can modify it the way you want from view

Upvotes: 3

Nhan Nguyen
Nhan Nguyen

Reputation: 495

<table>
            <tr ng-repeat-start="a in sevenWeekDayArr">
                <td>
                    {{a | date: 'shortDate'}}
                </td>
                <td>
                    <input type="hidden" ng-model="a.currDate" />
                </td>
            </tr>
            <tr>
                <td>Morning:</td>
                <td><input type="checkbox" ng-model="a.morning" /></td>
            </tr>
            <tr ng-repeat-end="">
                <td>Night:</td>
                <td><input type="checkbox" ng-model="a.night" /></td> 
            </tr>
</table>
<div>
    <button ng-click="addTime()">Click</button>
</div>

$scope.addTime = function(){
    angular.forEach($scope.sevenWeekDayArr, function(item){
      $scope.avail.push(item);
    });
    console.log($scope.avail);
};

Upvotes: 0

Related Questions