Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

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>
share|improve this question

1 Answer 1

up vote 2 down vote accepted

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.

share|improve this answer
    
Thank so much! Helps out a lot. – byrdr Aug 15 '14 at 23:46

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.