1

I have the following function which creates a new JSON object using data submitted through a form.

$scope.createEvent = function() {
  var cal = new CAL.API();
  cal.year = {August: [{day:$scope.calDay, title: $scope.calTitle, summary: $scope.calSummary, description: $scope.calDescrip}]};
  cal.$save(function(result){
    $scope.calendar.push(result);
  });
} 

I'd like to make the key, in this case the month August to be dynamic and pick up a $scope.calMonth field from the form. For some reason replacing the month with a dynamic $scope field doesn't seem to work. Is there any way to make this key value dynamic?

For reference here is my schema

year: { 
August: [
  {
    day: String,
    title: String,
    summary: String,
    description: String
  }
      ],
September: [
  {
    day: String,
    title: String,
    summary: String,
    description: String
  }
      ]
}
});

Here is my form:

<form name="calForm" ng-submit="createEvent()">
  <select ng-model="calMonth" required>
    <option>January</option>
    <option>February</option>
    <option>March</option>
    <option>April</option>
    <option>May</option>
    <option>June</option>
    <option>July</option>
    <option>August</option>
    <option>September</option>
    <option>October</option>
    <option>November</option>
    <option>December</option>
  </select>
  <input type="text" placeholder="Day" ng-model="calDay" required>
  <input type="text" placeholder="Title" ng-model="calTitle" required>
  <textarea type="text" placeholder="Summary" ng-model="calSummary" required></textarea>
  <br>
  <button class="addAdmin" type="submit">Add</button>
</form>

1 Answer 1

2

Try this:

var month = [{day:$scope.calDay, title: $scope.calTitle, summary: $scope.calSummary, description: $scope.calDescrip}];
cal.year = {};
cal.year[$scope.calMonth] = month;

Essentially you need to use the square bracket notation with dynamic key values. Also note setting the year to a blank object first, so that the dynamic month can be set.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.