【问题标题】:Angular JSON using $scope data as key value使用 $scope 数据作为键值的 Angular JSON
【发布时间】:2014-08-15 23:22:09
【问题描述】:

我有以下函数,它使用通过表单提交的数据创建一个新的 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);
  });
} 

我想设置键,在这种情况下,八月是动态的,并从表单中获取 $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>

【问题讨论】:

    标签: json angularjs rest


    【解决方案1】:

    试试这个:

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

    本质上,您需要将方括号表示法与动态键值一起使用。还要注意先将year设置为空白对象,这样才能设置动态月份。

    【讨论】:

    • 非常感谢!帮了大忙。
    猜你喜欢
    • 2019-07-15
    • 2019-05-04
    • 1970-01-01
    • 2015-09-11
    • 1970-01-01
    • 1970-01-01
    • 2020-01-27
    • 2019-03-16
    • 2019-05-24
    相关资源
    最近更新 更多