使用$ scope数据作为键值的Angular JSON

时间:2014-08-15 23:22:09

标签: json angularjs rest

我有以下函数,它使用通过表单提交的数据创建一个新的JSON对象。

$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);
  });
} 

我想制作密钥,在这种情况下,8月是动态的,并从表单中获取$ scope.calMonth字段。出于某种原因,用动态$ scope字段替换月份似乎不起作用。有没有办法让这个关键值动态化?

这里是参考我的架构

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

这是我的表格:

<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 个答案:

答案 0 :(得分:2)

试试这个:

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

基本上,您需要使用带有动态键值的方括号表示法。另请注意,首先将year设置为空白对象,以便设置动态月份。